gpt4 book ai didi

JavaFX FileChooser 在窗口为 "closed"后停止所有其他代码

转载 作者:行者123 更新时间:2023-11-30 07:23:41 37 4
gpt4 key购买 nike

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

在扩展Application的类中:

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;
}

但是“sup”永远不会打印到控制台。

我尝试过的

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

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

但是我们不能使用它,因为它会产生 IllegalStateException: Toolkit has exited。

我不想做的事情

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

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

最佳答案

简要说明

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

工作示例

所以我最终在扩展应用程序的类中做了什么:

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();
}
}

在调用应用程序的类中:

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);
}
}

关于JavaFX FileChooser 在窗口为 "closed"后停止所有其他代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37126096/

37 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com