检查组合框的空值时出错

时间:2013-01-22 12:50:25

标签: java

我有一个组合框和一个提交按钮,当提交按钮时,我想检查组合框的值是否为空。我使用这段代码:

ComboBox.setSelectedItem(null);
 if (ComboBox.getSelectedItem().equals(null)) {
           infoLabel.setText("Combo box value was null");
} 

当我按下提交按钮时出现此错误: 的 显示java.lang.NullPointerException

我该如何解决这个问题?

3 个答案:

答案 0 :(得分:2)

您无法将null引用给equals(),请执行以下操作:

ComboBox.setSelectedItem(null);
if (ComboBox.getSelectedItem() == null) {
  infoLabel.setText("Combo box value was null");
} 

这句话与您的问题无关:我建议使用Java Naming Convention,这会导致您的组合框被命名为comboBox(而不是{ {1}})。

答案 1 :(得分:2)

您无法在equals上致电null。而只需使用== null。 像这样:

ComboBox.setSelectedItem(null);
if (ComboBox.getSelectedItem() == null) {
    infoLabel.setText("Combo box value was null");
} 

应该工作。

答案 2 :(得分:1)

条件应该是:

ComboBox.getSelectedItem() != null

ComboBox.getSelectedItem().toString().equals("")

检查Combobox中选择的内容是空还是空

另一种方法是将第一个项目留空,然后检查所选索引是否为0,即

ComboBox.getSelectedIndex() != 0

由于

相关问题