我正在尝试从comboBox在JPanel中添加一些按钮。 comboBox有一个8个整数的数组,当其中一个被选中时,我希望能够按下一个go按钮,然后按钮将显示从组合框中选择的按钮数到JPanel中。
JPanel最初为空,并且在选择某些内容之前禁用了go按钮。
我已经创建了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);
}
}
答案 0 :(得分:1)
将ActionListener
附加到“开始”按钮。在actionPerformed
方法中,您需要从JComboBox
获取值,只需使用getSelectedValue
。这将返回Object
。检查对象是否为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);
}
}
}