我在学习JavaFx的过程中,遇到了一个问题。我尝试使用 JavaFx 中的 FileChooser,就像我习惯在 main() 方法中使用 Swing 中的 JFileChooser 一样。但是我发现我需要一个 Window 对象。我尝试寻找解决方法,但没有找到。我还尝试过 null (就像您在 JFileChooser 中所做的那样)和 new Stage(),所以这些都不在讨论之列。我试图模仿 JFileChooser.showOpenDialog()。有什么合理的方法让它发挥作用吗?
最佳答案
main
方法不在 FX 应用程序线程上执行,因此您无法从中显示 FileChooser
。 (在 Swing 中也不能真正做到这一点,除非您使用 SwingUtilities.invokeLater(...)
。)
在 JavaFX 中,启动应用程序的责任在 start()
方法中,该方法在 FX 应用程序线程上执行。 (在许多运行时环境中,您甚至不需要 JavaFX 应用程序中的 main
方法。)
只需从 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);
}
}
关于没有阶段的 JavaFx FileChooser,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37012911/