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

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

问题描述

我正在转换一个纯JavaFx应用程序,其中下面的代码在将所有内容放在一个类中时工作正常,到FXML,其中Stage声明和按钮处理程序在不同的类中。在Controller中,我正在尝试实现一种方法,允许用户选择一个目录并将其存储在一个变量中供以后使用:

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?

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

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