Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I print all the items within a JComboBox?

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.

like image 746
user1927670 Avatar asked Dec 25 '12 05:12

user1927670


2 Answers

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);
}
like image 69
Vimm Avatar answered Oct 13 '22 08:10

Vimm


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();
            }
        });
    }
}
like image 9
vels4j Avatar answered Oct 13 '22 09:10

vels4j