我有一个组合框和一个提交按钮,当提交按钮时,我想检查组合框的值是否为空。我使用这段代码:
ComboBox.setSelectedItem(null);
if (ComboBox.getSelectedItem().equals(null)) {
infoLabel.setText("Combo box value was null");
}
当我按下提交按钮时出现此错误: java.lang.NullPointerException
我怎样才能解决这个问题?
我有一个组合框和一个提交按钮,当提交按钮时,我想检查组合框的值是否为空。我使用这段代码:
ComboBox.setSelectedItem(null);
if (ComboBox.getSelectedItem().equals(null)) {
infoLabel.setText("Combo box value was null");
}
当我按下提交按钮时出现此错误: java.lang.NullPointerException
我怎样才能解决这个问题?
你不能给出null参考equals(),这样做:
ComboBox.setSelectedItem(null);
if (ComboBox.getSelectedItem() == null) {
infoLabel.setText("Combo box value was null");
}
还有一个与您的问题无关的评论:我建议使用Java Naming Convention,这将导致您的组合框被命名comboBox(而不是ComboBox)。
你不能打电话equals。null相反,只需使用== null. 像这样的东西:
ComboBox.setSelectedItem(null);
if (ComboBox.getSelectedItem() == null) {
infoLabel.setText("Combo box value was null");
}
应该管用。
条件应该是:
ComboBox.getSelectedItem() != null
或者
ComboBox.getSelectedItem().toString().equals("")
这将检查组合框中选择的内容是否为空或为空
另一种方法是将第一项留空,然后检查所选索引是否为 0,即
ComboBox.getSelectedIndex() != 0
谢谢