6

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user1927670
  • 61
  • 1
  • 1
  • 2
  • Would show us something regarding your item, what they are, and how you manipulate them... It would be better – Parth Soni Dec 25 '12 at 05:38
  • 4
    Simply get its model via `getModel()` then iterate through the model using the methods available from the `javax.swing.ListModel` interface which the model *must* imiplement. – Hovercraft Full Of Eels Dec 25 '12 at 05:42

2 Answers2

12

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);
}
martinez314
  • 12,162
  • 5
  • 36
  • 63
Vimm
  • 1,358
  • 1
  • 11
  • 12
9

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();
            }
        });
    }
}
vels4j
  • 11,208
  • 5
  • 38
  • 63