简体   繁体   English

JCombobox如何使用模型?

[英]JCombobox How to use model?

I'm trying to use Model which I set in Window Builder. 我正在尝试使用在Window Builder中设置的模型。

 'comboBox.setModel(new DefaultComboBoxModel(new String[] {"Easy", "Medium", "Hard"}));'

I Don't know how to use this text "Easy", "Medium", "Hard" in my If statment. 我在If语句中不知道如何使用此文本“ Easy”,“ Medium”,“ Hard”。 There is full code. 有完整的代码。

JComboBox comboBox = new JComboBox();
        comboBox.setMaximumRowCount(3);
        comboBox.setModel(new DefaultComboBoxModel(new String[] { "Easy",
                "Medium", "Hard" }));
        comboBox.setFont(new Font("Tahoma", Font.PLAIN, 16));
        comboBox.setBounds(101, 67, 194, 39);
        frame.getContentPane().add(comboBox);
        comboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent event) {
                if (event.getStateChange() == ItemEvent.SELECTED)
                    Snake.dificaulty = 1; // this variable is telling about difficulty level
            }

        });

It will be something like: 它将类似于:

String item = (String)comboBox.getSelectedItem();

You can then use this in the ItemListener. 然后,您可以在ItemListener中使用它。 If you are doing something complicated, write another method that does the complex stuff then call it from the itemStateChanged() method, passing the ItemEvent variable. 如果您要执行复杂的操作,请编写另一个执行复杂操作的方法,然后从itemStateChanged()方法中调用它,并传递ItemEvent变量。

In the ItemListener you can access the source of the event. ItemListener您可以访问事件的源。 Then you can access any property of the combo box. 然后,您可以访问组合框的任何属性。

JComboBox comboBox = (JComboBox)e.getSource();
String item = (String)comboBox.getSelectedItem();

No need to make the combo box final. 无需将组合框定为最终框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM