[英]How do I print all the items within a JComboBox?
I'm wondering how to print out ALL the items within a JComboBox. 我想知道如何在JComboBox中打印出所有项目。 I have no idea how to go about doing this.
我不知道该怎么做。 I know how to print out whatever item is selected.
我知道如何打印出所选的任何项目。 I just need it to where when I press a button, it prints out every option in the JComboBox.
我只需要它按下按钮的地方,它打印出JComboBox中的每个选项。
Check this 检查一下
public class GUI extends JFrame {
private JButton submitButton;
private JComboBox comboBox;
public GUI() {
super("List");
}
public void createAndShowGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
submitButton = new JButton("Ok");
Object[] valueA = new Object[] {
"StackOverflow","StackExcange","SuperUser"
};
comboBox = new JComboBox(valueA);
add(comboBox);
add(submitButton);
submitButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ComboBoxModel model = comboBox.getModel();
int size = model.getSize();
for(int i=0;i<size;i++) {
Object element = model.getElementAt(i);
System.out.println("Element at " + i + " = " + element);
}
}
});
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
GUI gui = new GUI();
gui.createAndShowGUI();
}
});
}
}
I know it's an old question, but I found it easier to skip the ComboBoxModel. 我知道这是一个老问题,但我发现跳过ComboBoxModel更容易。
String items = new String[]{"Rock", "Paper", "Scissors"};
JComboBox<String> comboBox = new JComboBox<>(items);
int size = comboBox.getItemCount();
for (int i = 0; i < size; i++) {
String item = comboBox.getItemAt(i);
System.out.println("Item at " + i + " = " + item);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.