6

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

4

2 回答 2

11

我知道这是一个老问题,但我发现跳过 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);
}
于 2016-11-23T20:56:02.543 回答
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();
            }
        });
    }
}
于 2012-12-25T05:58:59.983 回答