JavaFX FileChooser在窗口关闭后停止所有其他代码"

时间:2016-05-09 21:56:19

标签: java javafx

我当前项目的一部分是读取.txt日志文件,如果该日志文件不存在于其正常路径中,我想打开一个JavaFX FileChooser,让用户点到文件。但是在它的当前状态下它会弹出文件选择器窗口,在我指向.txt文件的位置之后,它只是空闲整个程序。

在扩展应用程序的类中:

public class GetDirectory extends Application {

    @Override
    public void start(final Stage primaryStage) {
        FileChooser fileChooser = new FileChooser();
        FileChooser.ExtensionFilter extFilter = new   FileChooser.ExtensionFilter("TXT files (*.txt)", "*.txt");
        fileChooser.getExtensionFilters().add(extFilter);
        File file = fileChooser.showOpenDialog(primaryStage);
        main.gamedata.LogReader logReader = new LogReader();
        logReader.setPathTemp(file.getAbsolutePath());
        primaryStage.close();
    }
}

另一个类中的方法中,我需要文件的路径:

    private List<String> getHearthstoneLogContent(String pathToFile) {
        try {
            File file = new File(pathToFile);
            if (file.exists() && !file.isDirectory()) {
                return Files.readAllLines(Paths.get(pathToFile));
            } else {
                // The out_log.txt file does not exist, we should let the user choose the path.
                Application.launch(GetDirectory.class);
                System.out.println("sup");
                return Files.readAllLines(Paths.get(pathTemp));
                }
            } catch (Exception e) {
                e.printStackTrace();
        }
        return null;
    }
然而,&#34; sup&#34;永远不会打印到控制台。

我尝试了什么

我认为这可能是因为应用程序没有关闭,所以我尝试使用:

    primaryStage.close();
    PlatformImpl.tkExit();
    Platform.exit();

但我们无法使用它,因为它会产生IllegalStateException:Toolkit已退出。

我不想做的事

我不想将我的所有代码都包装在JavaFX中,因为我只需要这么小的任务。

如果您想仔细查看相关项目: http://github.com/nymann/DeckSniffer/

1 个答案:

答案 0 :(得分:1)

简要说明

事实证明,为了只拥有一个FileChooser弹出窗口,你仍然需要使用primaryStage.show();和primaryStage.close();阻止它停止。然后,我通过将其不透明度设置为0,使得primaryStage不会短暂弹出,从而采用了一种hackish方式。

工作示例

所以我最终在扩展Application的类中做了什么:

public class test1 extends Application{
    public static String fileAsString;

    @Override
    public void start(Stage primaryStage) throws Exception {
        FileChooser fileChooser = new FileChooser();
        File file = fileChooser.showOpenDialog(primaryStage);
        fileAsString = file.getAbsolutePath();

        primaryStage.setOpacity(0);
        primaryStage.show();
        primaryStage.close();
    }
}

在从中调用Application的类中:

public class test2 {

    public test2() {
        testFromMethod();
    }

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

    private void testFromMethod() {
        System.out.println("Hello from testFromMethod()!");
        Application.launch(test1.class);
        System.out.println("Goodbye from testFromMethod()!");
        System.out.println(test1.fileAsString);
    }
}