Accessing FXML controller class

后端 未结 4 1214
再見小時候
再見小時候 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:09

    Another solution is to set the controller from your controller class, like so...

    public class Controller implements javafx.fxml.Initializable {
    
        @Override
        public void initialize(URL location, ResourceBundle resources) {
            // Implementing the Initializable interface means that this method
            // will be called when the controller instance is created
            App.setController(this);
        }
    
    }
    

    This is the solution I prefer to use since the code is somewhat messy to create a fully functional FXMLLoader instance which properly handles local resources etc

    @Override
    public void start(Stage stage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));
    }
    

    versus

    @Override
    public void start(Stage stage) throws Exception {
        URL location = getClass().getResource("/sample.fxml");
        FXMLLoader loader = createFXMLLoader(location);
        Parent root = loader.load(location.openStream());
    }
    
    public FXMLLoader createFXMLLoader(URL location) {
        return new FXMLLoader(location, null, new JavaFXBuilderFactory(), null, Charset.forName(FXMLLoader.DEFAULT_CHARSET_NAME));
    }
    

提交回复
热议问题