Reputation: 71
I'm wondering how to print out ALL the items within a 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.
Upvotes: 7
Views: 27046
Reputation: 1406
I know it's an old question, but I found it easier to skip the 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);
}
Upvotes: 13
Reputation: 11298
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();
}
});
}
}
Upvotes: 9