I have this code:

@Override public void start(Stage primaryStage) throws Exception{ Parent root = FXMLLoader.load(getClass().getResource("main.fxml")); primaryStage.setTitle("Hello World"); primaryStage.setScene(new Scene(root, 800, 600)); primaryStage.show(); } 

How can I make it so that from a completely separate controller class I replace main.fxml with server.fxml and display it accordingly?

  • Pass the name fxml in a separate parameter - Alex78191
  • @ Alex78191 Yes, it may well help, but how to get access to the primaryStage from another class to replace the scene? - Slava Nenashev
  • Pass the current stage - Alex78191
  • @ Alex78191 and not tell me how to do it? I tried, but I obviously somewhere was wrong. - Slava Nenashev

2 answers 2

Suppose so:

 public void onNewOrder(){ try { FXMLLoader loader = new FXMLLoader(); loader.setLocation(getClass().getResource("/Order/OrderNew.fxml")); Parent page = loader.load(); Stage stage = new Stage(); stage.setScene(new Scene(page)); WeakReference<OrderNewController> newOrd = new WeakReference<OrderNewController>(loader.getController()); newOrd.get().setStage(stage); stage.show(); } catch (IOException ex) { logger.error(ex.getMessage()); } } 

Correspondingly, a setter for the Stage was created in the OrderNewController class and then used in it. It is also possible to pass through some kind of class that implements a SharedPreference.

For example, in the controller, we handle closing the window:

  public void setStage(Stage stage) { this.stage=stage; this.stage.setOnCloseRequest(new EventHandler<WindowEvent>() { public void handle(WindowEvent we) { //обработка } }); } 

Well, in fxml do not forget to explicitly identify the controller.

    I solved the problem easier. In the Main class I created a separate Stage and made it a reference to the main stage.

     public Stage MainStage; MainStage = primaryStage; 

    And to the controller

     @FXML public static Stage STAGE; public void serverMethod(ActionEvent actionEvent) throws Exception { Parent root = FXMLLoader.load(getClass().getResource("server.fxml")); STAGE.setScene(new Scene(root, 800, 600)); Server s = new Server(); s.startServer(); } 

    This is one of the easiest options.

    UPD: Be sure to create a separate controller, unfortunately you cannot use one controller for several fxml. Also, if you need some code to start, when replacing the scene, then use initialize .