在javaFX中切换场景 [英] Switching scene in javaFX

查看:111
本文介绍了在javaFX中切换场景的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在选择menuItem时尝试关闭当前场景并打开另一个场景时遇到问题。我的主要阶段编码如下:

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

然后在createProduct.fxml中,当menuItem是onclick时,它将执行以下操作:

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

它打开了createCategory.fxml。但是,之前的createProduct.fxml面板不会关闭。我知道有一些叫做stage.close()来做这件事,但是我不知道在哪里实现它,因为我没有从一开始就从主右边传递场景。我想知道该如何解决这个问题。

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.

提前致谢。

推荐答案

你必须在start方法中做一些更改,比如..

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

,你的CreateProductController.java将是,

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

}

这篇关于在javaFX中切换场景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆