JavaFX中的FXML控制器实例返回null

时间:2016-04-07 16:05:14

标签: javafx controller null fxml

我想通过Class Main中的这一行为FXML Controller创建一个引用

Controller controller = (Controller) loader.getController();

可以从Class GrblListener访问Controller方法。

Main.controller.updateCurrentPosition(input);

但我总是得到错误

Exception in thread "EventThread COM5" java.lang.NullPointerException

怎么了?

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

1 个答案:

答案 0 :(得分:2)

您在start()中声明了一个局部变量,并将其初始化:

Controller controller = (Controller) loader.getController();

而不是初始化您声明的static变量:

public static Controller controller ;

public void start(Stage stage) {

    controller = (Controller) loader.getController();

    // ...
}