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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14027949/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 14:48:21  来源:igfitidea点击:

How do I print all the items within a JComboBox?

javaswingjcomboboxcomboboxmodel

提问by user1927670

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.

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

回答by vels4j

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

回答by Vimm

I know it's an old question, but I found it easier to skip the ComboBoxModel.

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