【问题标题】:How to switch to new scenes without an Mouse/Drag/etc. event?如何在没有鼠标/拖动/等的情况下切换到新场景。事件?
【发布时间】:2020-01-04 01:12:59
【问题描述】:

在我的代码中,我可以使用如下按钮切换到另一个场景:

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

现在我在控制器类中有一个方法,它应该打开一个没有事件的场景:

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

问题是,我不知道如何获取舞台的节点,这个程序只有在我打开一个全新的舞台/窗口时才能工作。

如何在没有事件和打开新阶段的情况下切换到新场景?

【问题讨论】:

    标签: java javafx fxml


    【解决方案1】:

    您可以使用控制器类中的任何@FXML 注入节点,

    假设你有一个按钮

    @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 在控制器初始化并注入节点后执行。

    【讨论】:

    • 问题是这个场景不包含任何按钮,只是一个带有 Imageviews 的 Gridpane。你的意思是显示按钮,一个对用户不可见的虚拟按钮,只能通过 showResult() 方法激活?
    • 虚拟按钮?不!我的意思是使用任何注入节点,这意味着用@FXML 注释。在您的情况下,您似乎已经注入了图像视图和网格窗格。你可以使用它们中的任何一个。您可以使用@FXML 变量更新您的问题 - 这样我就可以在我的回答中反映出来
    猜你喜欢
    • 1970-01-01
    • 2022-01-25
    • 2011-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 2011-09-22
    相关资源
    最近更新 更多