0

I created a ListView with three options in it and I want to draw a triangle with a certain color depending on what option in the ListView that is selected.

       String vald = categoryList.getSelectionModel().getSelectedItem();

            Triangle triangle = new Triangle(x,y);
            if(vald.equals("Bus")) {
                triangle.setFill(Color.BLACK);
            }
            else {
                triangle.setFill(Color.YELLOW);
            }
            center.getChildren().add(triangle);

It works when I select any of the three options. Problem is when I start up the program and dont select anything in the List, it gives me a nullpointer exception and points to the vald.equals("Bus") and the package declaration. When I remove the code for the listview check it works tho. So I'm wondering if I'm missing something when checking for items in a ListView. (I checked if it worked with radiobuttons instead and it did so I'm at a dead end)

skyy6
  • 1
  • Just change the order of your equals check to `"Bus".equals(vald)` and it will be safe from NPEs. (Because `"Bus"` cannot be `null`, while `vald` can be `null` and trying to call equals method on a null object is what is causing the NPE) – OH GOD SPIDERS May 04 '20 at 14:30
  • @OHGODSPIDERS ah wonderful! Thanks and yeah it did! tysm – skyy6 May 04 '20 at 14:37

0 Answers0