简体   繁体   中英

JCombobox How to use model?

I'm trying to use Model which I set in 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. 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. 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.

In the ItemListener you can access the source of the event. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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