我在选择menuItem时关闭当前场景并打开另一个场景时遇到问题.我的主要阶段编码如下:
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时,它将执行以下操作:
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()的东西要做这个,但我不知道在哪里实现它,因为我没有从一开始就从主右侧传递场景.我想知道我应该怎么解决这个问题.
提前致谢.
解决方法
您必须在start方法中进行一些更改,例如..
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将是,
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(); } }