Reputation: 2854
I've been away from Java for some years and have started to pick it up again a couple of days ago. I'll need to create a GUI using FXML and to get some practice I'm implementing a little chat application as an exercise.
I want to create a background thread which listens on a port and sends received messages to a textArea. By what I've read, this is best done by using the 'javafx.concurrent' package.
So I came up with the following:
import javafx.concurrent.Service;
import javafx.concurrent.Task;
public class ListenOnPort extends Service<Void> {
@Override protected Task<Void> createTask() {
return new Task<Void>() {
@Override protected Void call() throws Exception {
updateMessage("Bla!");
/*
int max = 50;
for (int i = 1; i <= max; i++) {
updateProgress(i, max);
updateMessage(String.valueOf(i));
Thread.sleep(50);
}
*/
return null;
} //call()
};
} //createTask()
}// ListenOnPort
The [shortened] controller is:
public class FXMLDocumentController {
@FXML private Label status;
@FXML private ProgressBar progressBar;
ListenOnPort listenService;
@FXML void startListening(ActionEvent event) {
localPort = Integer.parseInt(listenPort.getText());
status.setText("Attempting to open local port " +localPort +" for listening.");
listenService.start();
}
@FXML void initialize() {
// assertions
listenService = new ListenOnPort();
/*>>>*/ progressBar.progressProperty().bind(listenService.progressProperty());
status.textProperty().bind(listenService.messageProperty());
}
}
Which results in:
java.lang.NullPointerException
at p2pchat.FXMLDocumentController.initialize(FXMLDocumentController.java:130)
Line 130 is the second to last line of code, marked with '/>>>/'.
Why do I get a nullPointerException? What am i doing wrong?
Upvotes: 0
Views: 803
Reputation: 3396
First, make sure you created a ProgressBar
element in the .fxml file with an fx:id
of progressBar
.
Then in your IDE click in your project folder and press F5
, it will refresh the .fxml and it will see the most updated version. Otherwise the IDE will not see the recent modifications you've made to your .fxml file and will cause the NullPointerException
.
Upvotes: 2