简体   繁体   中英

Getting error when checking combobox for null value

I got a combobox, and a submit button, when the button is submitted, i want to check if the combobox value was null. Im using this code:

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

i am getting this error when i press the submit button: java.lang.NullPointerException

how can i fix this?

You can not give the null reference to equals() , do it like this:

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

And a remark that has nothing to do with your question: I suggest using the Java Naming Convention , which would lead to your combo box being named comboBox (and not ComboBox ).

You can not call equals on null . Instead simply use == null . Something like this:

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

Should work.

The condition should be :

ComboBox.getSelectedItem() != null

or

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

This checks if what is selected in the Combobox is null or empty

Another way of doing this is leaving the first item empty, then check for the selected index against 0 ie

ComboBox.getSelectedIndex() != 0

Thanks

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