user5047031
user5047031

Reputation: 25

Random NullPointerExceptions in JavaFX

My first question on SO.

So I am just starting to learn JavaFX, and I already have taken a year of normal Java coding at school, so I was a bit perplexed when I came across this problem:

I started creating a basic GUI in JavaFX Scene Builder which has a few buttons, a textField, and a statusIndicator, and when I click buttonListen I want buttonToggle to disappear and have the status indicator (spinWheel) appear. Here is the code for handling that:

@FXML
private TextField fieldDisplay;
private Button buttonToggle;
private Button buttonListen;
private ProgressIndicator spinWheel;

@FXML
private void ButtonListenListener(ActionEvent event){
    if(buttonToggle.isVisible()){
        buttonToggle.setVisible(false);
        spinWheel.setVisible(true);
    }
}   

All of that is contained within an FXMLDocumentController.java class for those familiar with JavaFX. However, when I run the program, there is a big long error stack, but it boils down to this statement saying that there is a nullPointer on one of my Buttons:

Caused by: java.lang.NullPointerException
at javafxfirstproj.FXMLDocumentController.ButtonListenListener(FXMLDocumentController.java:45)

I've heard that JavaFX is riddled with bugs, so I'm wondering if this is a logic error in my code or if I've just run into one of the (supposedly) many bugs. Any and all help would be appreciated. Thanks.

Upvotes: 1

Views: 110

Answers (2)

Sarfaraz Khan
Sarfaraz Khan

Reputation: 2186

If you are creating/declaring of Javafx components/nodes/control in FXML and you want to use it in the Java controller class then with each and every component that you want to use should have @FXML annotation with them. So in you code add FXML annotations

@FXML
private TextField fieldDisplay;
@FXML
private Button buttonToggle;
@FXML
private Button buttonListen;
@FXML
private ProgressIndicator spinWheel;

If you don't then these components are not assigned any objects thus when you use it like this

if(buttonToggle.isVisible())

it will give you NullPointerException

Checkout this blog's Connection to code section

Upvotes: 0

Sam Estep
Sam Estep

Reputation: 13304

I'd need to see more of your code (specifically, the FXML and the code that loads it) to be sure, but I'm guessing the problem is here:

@FXML
private TextField fieldDisplay;
private Button buttonToggle;
private Button buttonListen;
private ProgressIndicator spinWheel;

That @FXML notation only applies to the declaration immediately following it (the declaration of fieldDisplay). If buttonToggle, buttonListen, and spinWheel are also linked to FXML, you need to annotate each of them as well:

@FXML
private TextField fieldDisplay;
@FXML
private Button buttonToggle;
@FXML
private Button buttonListen;
@FXML
private ProgressIndicator spinWheel;

Upvotes: 3

Related Questions