简体   繁体   English

没有Stage的JavaFx FileChooser

[英]JavaFx FileChooser without Stage

I am in the process of learnig JavaFx, and I encountered a problem. 我正在学习JavaFx,我遇到了一个问题。 I was trying to use FileChooser from JavaFx the way I was used to working with JFileChooser from Swing-in the main() method. 我试图使用JavaFx中的FileChooser,就像我习惯使用来自Swing的JFileChooser的main()方法一样。 However I found out that I need a Window object. 但是我发现我需要一个Window对象。 I've tried searching for a workaround, but I found none. 我试过寻找一种解决方法,但我找不到。 I've also tried null (as you do in JFileChooser) and new Stage(), so those are off the table. 我也尝试过null(就像你在JFileChooser中那样)和新的Stage(),所以这些都不在桌面上。 I was trying to mimic the JFileChooser.showOpenDialog(). 我试图模仿JFileChooser.showOpenDialog()。 Is there any reasonable way to make it work? 有没有合理的方法让它发挥作用?

The main method is not executed on the FX Application Thread, so you can't show a FileChooser from it. main方法不在FX应用程序线程上执行,因此您无法从中显示FileChooser (You can't really do that in Swing either, unless you are using SwingUtilities.invokeLater(...) .) (你不能在Swing中真正做到这一点,除非你使用的是SwingUtilities.invokeLater(...) 。)

In JavaFX, the responsibility for starting the application is in the start() method, which is executed on the FX Application Thread. 在JavaFX中,启动应用程序的责任在start()方法中,该方法在FX Application Thread上执行。 (In many runtime environments, you don't even need a main method in JavaFX applications.) (在许多运行时环境中,您甚至不需要JavaFX应用程序中的main方法。)

Just show the file chooser from the start method, where you have access to the primaryStage (or can just pass null , if you like): 只需从start方法显示文件选择器,您可以在其中访问primaryStage (或者如果您愿意,可以只传递null ):

public class MyApp extends Application {

    public void start(Stage primaryStage) {
        FileChooser configFileChooser = new FileChooser();
        File configFile = configFileChooser.showOpenDialog(primaryStage);

        // ... parse file and create UI, etc...

        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM