我正在尝试从组合框在 JPanel 中添加一些按钮。组合框有一个 8 个整数的数组,当选择其中一个时,我希望能够按下“执行”按钮,然后将从组合框中选择的按钮数量显示到 JPanel 中。
JPanel 最初是空的,并且“执行”按钮被禁用,直到选择某些内容为止。
我已经创建了 JPanel、comboBox 和 go 按钮,但我现在不知道如何获取和创建按钮。
充满字符串的组合框 -
String[] floorStrings = {"Select one", "1", "2", "3", "4", "5", "6", "7", "8"};
//Create the combo box
JComboBox floorList = new JComboBox(floorStrings);
actionPerformed 代码 -
public void actionPerformed(ActionEvent e) {
floorList.getSelectedIndex();
//int i = Integer.valueOf((String) floorList);
if (e.getSource() == go) {
go.setText("Stop");
System.out.print("Clicked " + floorList);
p3.add(go, BorderLayout.NORTH);
}
}
最佳答案
将 ActionListener
附加到“Go”按钮。在 actionPerformed
方法中,您需要从 JComboBox
获取值,只需使用 getSelectedValue
即可。这将返回一个对象
。检查该对象是否不为 null
并尝试将其转换为 int
(即 (int)value
)。
如果转换成功,只需创建一个 for-next
循环,根据组合框中的值循环 n
次并创建按钮,将它们添加到您的面板中。
看看How to Write an Action Listener和 How to use Combo Boxes和 The for Statement了解更多详情
用示例更新
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.management.StringValueExp;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
public class TestComboBox08 {
public static void main(String[] args) {
new TestComboBox08();
}
public TestComboBox08() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
}
JFrame frame = new JFrame("Test");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JComboBox floorList;
private JPanel buttons;
public TestPane() {
setLayout(new BorderLayout());
String[] floorStrings = {"Select one", "1", "2", "3", "4", "5", "6", "7", "8"};
floorList = new JComboBox(floorStrings);
JButton go = new JButton("Go");
go.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int count = floorList.getSelectedIndex();
buttons.removeAll();
for (int index = 0; index < count; index++) {
buttons.add(new JButton(String.valueOf(index)));
}
buttons.revalidate();
}
});
JPanel top = new JPanel(new FlowLayout(FlowLayout.CENTER));
top.add(floorList);
top.add(go);
buttons = new JPanel(new GridLayout(0, 4));
buttons.setPreferredSize(new Dimension(200, 200));
add(top, BorderLayout.NORTH);
add(buttons);
}
}
}
关于java - 如何从组合框中的数字列表向 JPanel 添加按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15938862/