如何打印JComboBox中的所有项目?

时间:2012-12-25 05:26:38

标签: java swing jcombobox comboboxmodel

我想知道如何在JComboBox中打印出所有项目。我不知道该怎么做。我知道如何打印出所选的任何项目。我只需要按下按钮,它就会打印出JComboBox中的每个选项。

2 个答案:

答案 0 :(得分:9)

检查

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();
            }
        });
    }
}

答案 1 :(得分:5)

我知道这是一个老问题,但我发现跳过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);
}