0

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);
            }
        }
    }
}
4
  • How to you connect the controller? Manually? Or in FXML? Haven't you forgot fx:controller="Controller" in FXML? Commented Apr 7, 2016 at 16:32
  • I created the FXML with SceenBuilder, so I connect with fx:controller="package.Controller". Commented Apr 7, 2016 at 16:44
  • For now I avoid the problem by creating a public variable in the Class GrblListener which I then check with a timer every second in Class Controller to trigger the action ... Not the best solution ... Commented Apr 7, 2016 at 16:48
  • What's wrong with the solution I posted? Commented Apr 7, 2016 at 17:30

1 Answer 1

2

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();

    // ...
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.