Java ComboBox - 打印出所选项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4024392/
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-08-14 08:37:36  来源:igfitidea点击:

ComboBox - printing out the selected item

javauser-interfaceswingcomboboxjcombobox

提问by tom

I am a little stuck. I can't figure out a much bigger problem than this, so I am going to the roots to eventually build my way up!

我有点卡住了。我想不出比这更大的问题,所以我要从根源开始,最终建立自己的道路!

I can't print the selected item in the combo box, currently I have an ActionListenerfor it:

我无法在组合框中打印所选项目,目前我有一个ActionListener

box.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent evt) {
        myBox(evt);
    }
});

...

protected void myBox(ActionEvent evt)
{
    if(myBoxName.getSelectedItem().toString() != null)
    System.out.println(myBoxName.getSelectedItem().toString());
}

I would expect this to print out to the console every time I change the selected item, but it doesn't. This should be so easy though!

我希望每次更改所选项目时都会将其打印到控制台,但事实并非如此。不过,这应该很容易!

Thanks

谢谢

采纳答案by Peter Lang

I just tried your code and it works fine. Whenever I change selection, the selected text is written to System.out.

我刚刚试过你的代码,它工作正常。每当我更改选择时,选定的文本都会写入System.out.

The only thing I changed was the check for myBoxName.getSelectedItem().toString() != null, I check for myBoxName.getSelectedItem() != nullinstead. This should not be related to your problems though.

我唯一改变的是检查myBoxName.getSelectedItem().toString() != null,我myBoxName.getSelectedItem() != null改为检查。不过,这不应该与您的问题有关。

public class ComboBoxTest {
    private JComboBox comboBox = new JComboBox(
          new DefaultComboBoxModel(new String[] { "Test1", "Test2", "Test3" }));

    public ComboBoxTest() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        frame.setSize(200, 100);

        comboBox.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent evt) {
                myBox(evt);
            }
        });

        frame.getContentPane().add(comboBox);
        frame.setVisible(true);
    }

    protected void myBox(ActionEvent evt) {
        if (comboBox.getSelectedItem() != null) {
            System.out.println(comboBox.getSelectedItem().toString());
        }
    }
}