如何从控制器访问 JavaFx Stage? [英] How to access a JavaFx Stage from a Controller?

查看:40
本文介绍了如何从控制器访问 JavaFx Stage?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个纯 JavaFx 应用程序(其中下面的代码在将所有内容放在一个类中时运行良好)转换为 FXML 应用程序,其中 Stage 声明和按钮处理程序位于不同的类中.在控制器中,我试图实现一种方法,该方法将允许用户选择一个目录并将其存储在一个变量中以备后用:

I'm converting a pure JavaFx app, in which the code below worked fine when put all in one class, to a FXML one, where the Stage declaration and the button handler are in separate classes. In the a Controller, I'm trying to implement a method that will allow the user to choose a directory and store it in a variable for later use:

private File sourceFile;
DirectoryChooser sourceDirectoryChooser;

@FXML
private void handleSourceBrowse() {
        sourceDirectoryChooser.setTitle("Choose the source folder");
        sourceFile = sourceDirectoryChooser.showDialog(theStage);
}

然而,theStage",该方法需要的一个舞台,只存在于 FolderSyncer4.java 中(如果这是正确的术语):

However, "theStage", a Stage which the method requires, only exists(if that's the right terminology) in FolderSyncer4.java:

public class FolderSyncer4 extends Application {

    final String FOLDER_SYNCER = "FolderSyncer";

    Stage theStage;

    @Override
    public void start(Stage primaryStage) throws Exception {
        theStage = primaryStage;

        //TODO do the FXML stuff, hope this works
        Parent root = FXMLLoader.load(getClass().getResource("FolderSyncerMainWindow.fxml"));
        theStage.setScene(new Scene(root, 685, 550));
        theStage.setTitle(FOLDER_SYNCER);
        theStage.show();
    }
}

我该如何解决这个问题?我需要以某种方式再次实现该方法,但突然间我无法将阶段作为参数传递.

How to I get around this? I need to have that method implemented again somehow, but suddenly I can't pass the stage as an argument.

推荐答案

在您的情况下,从处理程序的 ActionEvent 参数获取场景可能是最简单的:

In your situation, it is probably easiest to get the scene from the ActionEvent parameter of your handler:

@FXML
private void handleSourceBrowse(ActionEvent ae) {
    Node source = (Node) ae.getSource();
    Window theStage = source.getScene().getWindow();

    sourceDirectoryChooser.showDialog(theStage);
}

参见 JavaFX:如何在初始化期间从控制器获取舞台? 了解更多信息.不过,我不赞成评分最高的答案,因为它在加载 .fxml 文件后向控制器添加了编译时依赖性(毕竟该问题被标记为 javafx-2,所以不确定上面的方法是否已经在那里工作,而且问题的上下文看起来有点不同).

See JavaFX: How to get stage from controller during initialization? for some more information. I am not in favor of the highest rated answer though, since it adds a compile time dependency to the controller after the .fxml file has been loaded (after all that question was tagged with javafx-2, so not sure if the above approach already worked there, and also the context of the question looks a bit different).

另见 如何打开来自控制器类的 JavaFX FileChooser?

这篇关于如何从控制器访问 JavaFx Stage?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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