Switching scene in javaFX

user2424370 picture user2424370 · Jun 21, 2013 · Viewed 36.1k times · Source

I have problem when trying to close current scene and open up another scene when menuItem is selected. My main stage is coded as below:

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 within createProduct.fxml, when menuItem is onclick, it will perform this:

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 opened up createCategory.fxml. However, the previous panel which is createProduct.fxml does not close. I know there's something called stage.close() to do this but I have no idea where to implement it since I not passing the scene from main right from the start. I wonder how should I fix this.

Thanks in advance.

Answer

Shreyas Dave picture Shreyas Dave · Jun 21, 2013

You have to make some changes in start method, like..

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

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

}