在我的代码中,我可以使用如下按钮切换到另一个场景:
public void handleButtonClick(MouseEvent event) throws IOException {
Parent menu_parent = FXMLLoader.load(getClass().getResource("/FXML/FXMLmm2.fxml"));
Scene SceneMenu = new Scene(menu_parent);
Stage stage = (Stage) ((Node) event.getSource()).getScene().getWindow();
stage.setScene(SceneMenu);
stage.show();
}
现在我在 Controller 类中有一个方法,它应该打开一个没有事件的场景:
public void showResult(boolean win) throws IOException {
if (win == true) {
Parent menu_parent = FXMLLoader.load(getClass().getResource("/FXML/FXMLWinScreen.fxml"));
Scene SceneMenu = new Scene(menu_parent);
Stage stage = new Stage();
stage.setScene(SceneMenu);
stage.show();
}
问题是,我不知道如何获取舞台的节点,这个程序只有当我打开一个全新的舞台/窗口时才起作用。
如何在没有事件的情况下切换到新场景并打开新阶段?
最佳答案
您可以使用 Controller 类中的任何@FXML
注入(inject)节点,
假设您有一个按钮
@FXML private Button show;
现在使用该按钮 show.getParent().getScene().getWindow()
获取当前舞台,
public void showResult(boolean win) throws IOException {
if (win == true) {
Parent menu_parent = FXMLLoader.load(getClass()
.getResource("/FXML/FXMLWinScreen.fxml"));
Scene SceneMenu = new Scene(menu_parent);
Stage stage = (Stage)show.getParent().getScene().getWindow();
stage.setScene(SceneMenu);
stage.show();
}
}
但请确保 showResult
在 Controller 初始化并注入(inject)节点后执行。
关于java - 如何在不使用鼠标/拖动等的情况下切换到新场景。事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59587115/