Switch scenes in JavaFX

I have a problem closing the current scene and opening another scene when selecting MenuItem My main stage codes are as follows:

public void start(Stage primaryStage) throws Exception {
   primaryStage.setTitle("Shop Management");
   Pane myPane = (Pane)FXMLLoader.load(getClass().getResource
("createProduct.fxml"));
   Scene myScene = new Scene(myPane);        
   primaryStage.setScene(myScene);
   primaryStage.show();
}

Then in createproduct In fxml, when MenuItem is onclick, it will perform the following operations:

public void gotoCreateCategory(ActionEvent event) throws IOException {
    Stage stage = new Stage();
    stage.setTitle("Shop Management");
    Pane myPane = null;
    myPane = FXMLLoader.load(getClass().getResource("createCategory.fxml"));
    Scene scene = new Scene(myPane);
    stage.setScene(scene);
    stage.show();
}

It does open createcategory fxml. However, the previous createproduct The fxml panel does not close I know one called stage Close () does this, but I don't know where to implement it, because I didn't pass the scene from the main right from the beginning I wonder how I should solve this problem

Thank you in advance

Solution

You must make some changes in the start method, such as

public void start(Stage primaryStage) throws Exception {
   primaryStage.setTitle("Shop Management");

   FXMLLoader myLoader = new FXMLLoader(getClass().getResource("createProduct.fxml"));

   Pane myPane = (Pane)myLoader.load();

   CreateProductController controller = (CreateProductController) myLoader.getController();

   controller.setPrevStage(primaryStage);

   Scene myScene = new Scene(myPane);        
   primaryStage.setScene(myScene);
   primaryStage.show();
}

Your createproductcontroller Java will be,

public class CreateProductController implements Initializable {

    Stage prevStage;

    public void setPrevStage(Stage stage){
         this.prevStage = stage;
    }

    @Override
    public void initialize(URL location,ResourceBundle resources) {
    }

    public void gotoCreateCategory(ActionEvent event) throws IOException {
       Stage stage = new Stage();
       stage.setTitle("Shop Management");
       Pane myPane = null;
       myPane = FXMLLoader.load(getClass().getResource("createCategory.fxml"));
       Scene scene = new Scene(myPane);
       stage.setScene(scene);

       prevStage.close();

       stage.show();
    }

}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>