【发布时间】:2015-02-01 14:45:12
【问题描述】:
我已经(几乎)到处寻找(here 和 here 特别是)以找到我的问题的答案。我正在尝试将未知数量的JButton 添加到JScrollPane,具体取决于JComboBox 的选择。我所知道的是,您必须将元素添加到 JPanel 才能将它们放入您的 GUI。
这是一个示例代码: (它不起作用),这是一个例子)
public class test {
ArrayList<JButton> button = new ArrayList<JButton>();
String[] stringArray = {"Goat", "Cow", "Dog", "Cat", "Human"};
JComboBox comboBox = new JComboBox(stringArray);
JPanel containerPanel = new JPanel();
JScrollPane scroller = new JScrollPane(containerPanel);
public void addButton(String btnName) {
button.add(new JButton(btnName));
containerPanel.add(button.get(button.size() - 1));
}
public class Action implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
addButton(comboBox.getSelectedItem().toString());
}
}
}
我想根据用户的需要添加任意数量的JButton。
如果我像这样添加它们:
containerPanel.add(new JButton("test"));
它有效,但这不是我想要实现的目标。
你能帮帮我吗?
编辑: ___________________________________________________________________________
这是一些可以编译的代码,是我正在尝试做的简化副本:
public class Frame extends JFrame {
String[] list = {"Human", "Goat", "Dog", "Cat", "Duck"};
ArrayList<JButton> button = new ArrayList<JButton>();
JComboBox cBox = new JComboBox(list);
JPanel container = new JPanel();
JScrollPane scroller = new JScrollPane(container);
public Frame() {
cBox.addActionListener(new Action());
this.setLayout(new BorderLayout());
this.setSize(200, 200);
this.add(cBox, BorderLayout.SOUTH);
this.add(scroller, BorderLayout.CENTER);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setVisible(true);
}
public void createBtn(String s) {
System.out.println("Button's label : " + s);
button.add(new JButton(s));
System.out.println("Button's index : " + (button.size() - 1));
container.add(button.get(button.size() - 1));
}
public class Action implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Action made");
JComboBox temp = (JComboBox) e.getSource();
createBtn(temp.getSelectedItem().toString());
}
}
}
【问题讨论】:
-
您列出了this question,但您却莫名其妙地忽略了使用合适布局(例如GridLayout)的答案-为什么?为什么不将 containerPanel 的布局设置为 GridLayout 并在其中添加按钮?
-
Ehm 只是使用循环添加任意数量的按钮?
-
@HovercraftFullOfEels 我尝试使用
BoxLayout和FlowLayout,但都没有。 -
@MuratK。问题是我不知道会有多少个按钮
-
Chax:除非我看到它,否则不要相信它——所以告诉我们。为了我的钱,我会使用 GridLayout,我会在连接到 JComboBox 的侦听器中的 for 循环中添加我的按钮。添加后,我会在按钮的容器上调用 revalidate 和 repaint,然后我就完成了。是的,你确实知道会有多少按钮。Comb 框会告诉你有多少项目已选中!
标签: java swing jbutton jscrollpane