问题很简单。单击一个按钮将添加另一个按钮。这也有效。但只有一次,我希望每次点击时都会在前一个按钮下方添加另一个按钮。
你能告诉我问题出在哪里吗?
这是我已经尝试过的: 不同的布局,因为我假设按钮位于彼此之上。 一个“GUI刷新”,因为我认为点击后界面应该更新......但它不起作用。 在我的最后一次尝试中,每次单击时我都会创建该类的一个新对象...不幸的是它也不起作用。
public class Main {
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new MVCView();
}
});
}
}
public class MVCView extends JFrame {
private static final long serialVersionUID = 1L;
public MVCView() {
init();
}
private void init() {
BorderLayout bl = new BorderLayout();
setLayout(bl);
this.setTitle("Test");
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
this.setExtendedState(this.MAXIMIZED_BOTH);
this.getContentPane().add(addNewRow(), BorderLayout.SOUTH);
this.pack();
this.setVisible(true);
}
public JComponent addNewRow() {
JPanel getSouthPanel = new JPanel();
getSouthPanel.setLayout(new BorderLayout());
JButton plus = new JButton("Add new Row");
plus.addActionListener(new MVCControllerAddLine(this));
getSouthPanel.add(plus, BorderLayout.SOUTH);
return getSouthPanel;
}
}
public class MVCControllerAddLine implements ActionListener{
private MVCView view;
MVCViewNodeContainer mvcViewNodeContainer = new MVCViewNodeContainer();
public MVCControllerAddLine(MVCView view) {
this.view = view;
}
@Override
public void actionPerformed(ActionEvent e) {
view.getContentPane().add(mvcViewNodeContainer.addNewNodeContainer());
view.revalidate();
view.validate();
view.repaint();
}
}
public class MVCViewNodeContainer{
private JPanel panel;
MVCView view;
public MVCViewNodeContainer() {
addNewNodeContainer();
}
public JComponent addNewNodeContainer() {
panel = new JPanel();
panel.setLayout(new GridBagLayout());
JButton addNode = new JButton("Add Node");
addNode.setPreferredSize(new Dimension(100, 120));
GridBagConstraints gbc = new GridBagConstraints();
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(4, 4, 4, 4);
gbc.gridwidth = 1;
gbc.gridheight = 1;
gbc.fill = GridBagConstraints.EAST;
gbc.anchor = GridBagConstraints.NORTHEAST;
gbc.weighty = 1;
gbc.weightx = 1;
panel.add(addNode, gbc);
panel.setMaximumSize(new Dimension(150, 100));
return panel;
}
}
如果您需要更多代码,请告诉我。我已尝试省略不必要的内容。
非常感谢您的帮助。
许多问候和愉快的周末
A456B123
最佳答案
我相信问题是您正在尝试使用 BorderLayout错误。
边框布局对容器进行布局,排列其组件并调整其大小以适应五个区域:北、南、东、西和中心。 每个区域只能包含一个组件,并由相应的常量标识:NORTH、SOUTH、EAST、WEST 和 CENTER。
您的代码在这里:
@Override
public void actionPerformed(ActionEvent e) {
view.getContentPane().add(mvcViewNodeContainer.addNewNodeContainer());
view.revalidate();
view.validate();
view.repaint();
}
每次都将“NodeContainers”添加到 BorderLayout 的同一区域。您需要将一个具有不同布局的面板放入其中一个区域,然后将按钮或“NodeContainers”添加到该面板。
关于java - 单击添加 GUI 元素仅有效一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55540903/