Accessing FXML controller class

后端 未结 4 1163
再見小時候
再見小時候 2020-11-22 07:51

I would like to communicate with a FXML controller class at any time, to update information on the screen from the main application or other stages.

Is this possible

4条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-22 08:28

    You can get the controller from the FXMLLoader

    FXMLLoader fxmlLoader = new FXMLLoader();
    Pane p = fxmlLoader.load(getClass().getResource("foo.fxml").openStream());
    FooController fooController = (FooController) fxmlLoader.getController();
    

    store it in your main stage and provide getFooController() getter method.
    From other classes or stages, every time when you need to refresh the loaded "foo.fxml" page, ask it from its controller:

    getFooController().updatePage(strData);
    

    updatePage() can be something like:

    // ...
    @FXML private Label lblData;
    // ...
    public void updatePage(String data){
        lblData.setText(data);
    }
    // ...
    

    in the FooController class.
    This way other page users do not bother about page's internal structure like what and where Label lblData is.

    Also look the https://stackoverflow.com/a/10718683/682495. In JavaFX 2.2 FXMLLoader is improved.

提交回复
热议问题