简体   繁体   中英

How to get the selected Item from a JComboBox in java and compare it to a string?

For my homework assignment I need to add 2 onto the total only if the combobox value that is selected is "deep dish"

'I have tried'

thickness.getSelectedItem().contentEquals("deep dish")
    {
        total += 2.00;
    }

the error that i am getting says that contentEquals is undefined for that type object and I do not know the correct way to do this. For clarity,

String[] choices = {"thin","original","deep dish"};
thickness = new JComboBox(choices);

Because JComboBox is a generic type. The constructor you used is pre Java 5 style. Means you don't get type checking provided by generics at compile time. My advice is to use an IDE, that highlights some of these obvious mistakes in your editor. The correct way to create a JComboBox is:

JComboBox<String> thickness = new JComboBox<String>(choices);

You see, thickness.getSelectedItem() will now return a string.

Edit

I just looked inside javax.swing.JComboBox.java and they disregard a generic type information for method getSelectedItem() :

    public Object getSelectedItem() {
        return dataModel.getSelectedItem();
    }

You have two options: 1) Continue using method contentEquals of type String , but do type casting explicitly in your code:

String selectedItem = (String) myComboBox.getSelectedItem();

if (selectedItem.contentEquals("Hello world!")) {
...
}
  1. This option is easier and relies on the fact that method equals of type Object is polymorphic for type String and you can safely call it instead. A general pattern is to call it on a constant string though (to avoid NullPointerException ):
if ("Hello Wolrd!".equals(myComboBox.getSelectedItem())) {
...
}

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