Reputation: 59
I want to create a reference for the FXML Controller by this line in Class Main
Controller controller = (Controller) loader.getController();
to have access to a Controller methode from the Class GrblListener.
Main.controller.updateCurrentPosition(input);
But I always get the error
Exception in thread "EventThread COM5" java.lang.NullPointerException
What's wrong?
Class Main:
public class Main extends Application {
public static Stage stage;
public static Controller controller;
@Override
public void start(Stage stage) throws Exception {
FXMLLoader loader = new FXMLLoader(getClass().getResource("Scene.fxml"));
Parent root = (Parent) loader.load();
Controller controller = (Controller) loader.getController();
Scene scene = new Scene(root);
scene.getStylesheets().add(getClass().getResource("css/default.css").toExternalForm());
stage.setTitle("...");
stage.setScene(scene);
stage.show();
this.stage = stage;
}
public static void main(String[] args) {
launch(args);
}
}
Class GrblListener:
class GrblListener implements SerialPortEventListener {
@Override
public void serialEvent(SerialPortEvent event) {
if(event.isRXCHAR() && event.getEventValue() > 0){
try {
String input = GrblSender.serialPort.readString();
System.out.println(input.trim());
Main.controller.updateCurrentPosition(input);
}
catch (SerialPortException ex) {
System.out.println(ex);
}
}
}
}
Upvotes: 0
Views: 789
Reputation: 209704
You are declaring a local variable in start()
, and initializing it:
Controller controller = (Controller) loader.getController();
instead of initializing the static
variable you declared:
public static Controller controller ;
public void start(Stage stage) {
controller = (Controller) loader.getController();
// ...
}
Upvotes: 2