0

I am working on a java project.The project works correctly but i need to use graphics and UI to make it cool,so i went on to use JavaFx.The plan is simple.I am using a external file to call a number and depending on if the number is divisible by 2 or not,the three buttons will have different background color;red or green.I used setStyle to change background color according to the input,it gives Null Pointer Exception,i don't understand if the program is in logic of the program or some other thing.(The input and output both works correctly in java application) The variable k is different part of my program but it works correctly and it will return either 1 or 0.

   File file = new File("count.txt");
      Scanner scanner = new Scanner(file);
      int count =0;

    while(scanner.hasNextInt()){
        count =scanner.nextInt();
    }

    if (k == 0){
    if ( count % 2 == 1){        


   waterButton.setStyle("-fx-background-color: #ff0000; ");
    waterButton2.setStyle("-fx-background-color: green");
   waterButton3.setStyle("-fx-background-color: green");

    }    
    else if (count % 2 ==0) {

   waterButton.setStyle("-fx-background-color: green");
   waterButton2.setStyle("-fx-background-color: green");
   waterButton3.setStyle("-fx-background-color: green");
    }
 }
 else {

waterButton.setStyle("-fx-background-color: #ff0000; ");
waterButton2.setStyle("-fx-background-color: #ff0000; ");
waterButton3.setStyle("-fx-background-color: #ff0000; ");
System.exit(0);
}
      }catch (IOException e){
          System.out.println(e.getMessage());
      }

////

 NullPointerException: waterButton.setStyle("-fx-background-color: #ff0000; ");
Meet Yeole
  • 71
  • 2
  • 8

1 Answers1

2

The NullPointerException on the line waterButton.setStyle("-fx-background-color: #ff0000; "); clearly tells that the variable waterButton is null (like one would already have guessed).

Because you said your program was working I assume that the code you posted is in the constructor of the class (or called from the constructor), because in the constructor the FXML parts are not initialized, which means all fields annotated with @FXML are null until the initialize method is called (which is called after the construction of the object).

This behaviour can't be changed, because thats just how the injection of FXML works, but if you place your code in the initialize method of your class it should work.

Tobias
  • 2,547
  • 3
  • 14
  • 29