简体   繁体   English

如何从 java 中的 JComboBox 中获取所选项目并将其与字符串进行比较?

[英]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" 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.我得到的错误是 contentEquals 未定义该类型 object,我不知道执行此操作的正确方法。 For clarity,为了清楚起见,

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

Because JComboBox is a generic type.因为 JComboBox 是泛型类型。 The constructor you used is pre Java 5 style.您使用的构造函数是 pre Java 5 样式。 Means you don't get type checking provided by generics at compile time.意味着您不会在编译时获得 generics 提供的类型检查。 My advice is to use an IDE, that highlights some of these obvious mistakes in your editor.我的建议是使用 IDE,它会突出显示您的编辑器中的一些明显错误。 The correct way to create a JComboBox is:创建 JComboBox 的正确方法是:

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

You see, thickness.getSelectedItem() will now return a string.你看, thickness.getSelectedItem()现在将返回一个字符串。

Edit编辑

I just looked inside javax.swing.JComboBox.java and they disregard a generic type information for method getSelectedItem() :我只是查看了javax.swing.JComboBox.java ,他们忽略了方法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:您有两个选择:1) 继续使用String类型的方法contentEquals ,但在您的代码中显式进行类型转换:

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.此选项更简单,并且依赖于Object类型的方法equals对于String类型是多态的,您可以安全地调用它。 A general pattern is to call it on a constant string though (to avoid NullPointerException ):通用模式是在常量字符串上调用它(以避免NullPointerException ):
if ("Hello Wolrd!".equals(myComboBox.getSelectedItem())) {
...
}

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

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