0
votes

I´m writing a program where different symbols are drawn on an image based on what the user selects in a JList. This works fine, but my problem is that I want to place a symbol on the image if nothing is selected in the JList as well. Is there some way to check if the selection is empty? This is my code right now, and it throws me a NullPointerException if I don´t select anything from the JList.

if(categoriesList.getSelectedValue().equals("Bus")) {
            BusSymbol bs = new BusSymbol(x, y);
            mp.add(bs);
        } 
        else if 
(categoriesList.getSelectedValue().equals("Underground")) {
            UndergroundSymbol us = new UndergroundSymbol(x,y);
            mp.add(us);
        }
        else if (categoriesList.getSelectedValue().equals("Train")) {
            TrainSymbol ts = new TrainSymbol(x,y);
            mp.add(ts);
        }
        else if (categoriesList.getSelectedValue().equals(null)) {

            NoCategorySymbol ncs = new NoCategorySymbol(x,y);
            mp.add(ncs);
        }

        mp.validate();
        mp.repaint();
3
That's because null has no .equals method. If something might be null, you want to check it with == null (or ideally with another method ; isn't there a hasSelectedValue() method on that API ?) - Aaron

3 Answers

0
votes

You should use JList.isSelectionEmpty() as a condition instead of testing against the value that might be null.

You should either make this test first, and/or change all the other tests which have this unfortunate syntax :

mightBeNull.equals(neverNull)

As a general rule it is generally better to avoid this syntax and use neverNull.equals(mightBeNull) instead, as it avoids attempting to invoke the inexistant null.equals() method.

I propose the following code :

if (categoriesList.isSelectionEmpty()) {
    mp.add(new NoCategorySymbol(x,y));
} else {
    // here we know categoriesList.getSelectedValue() isn't null
    String selectedValue = categoriesList.getSelectedValue());
    if ("Underground".equals(selectedValue)) {
       mp.add(new UndergroundSymbol(x,y));
    } else if ("Train".equals(selectedValue)) {
       mp.add(new TrainSymbol(x, y));
    }
}
mp.validate();
mp.repaint();
0
votes

You can't check for a null value using .equals you need to use ==.

categoriesList.getSelectedValue() == null

This is because .equals calls a method on the object. If the object is null you can't do that.

0
votes
public boolean isElementSelected(){ return categoriesList.getSelectedValue() == null;}