java - 文件选择器对话框未关闭

标签 java javafx-2 javafx

这是我的文件选择器对话框操作代码...

FileChooser fc = new FileChooser();
fc.setTitle("Pointel File");
File file1 = fc.showOpenDialog(MainFrame.objComponent.getPrimaryStage());

int i =0;
while(i < 90000){
System.out.println(i);
i++;
}

在上面的代码中,对话框等待“while”循环完成执行,而不是在我们单击“打开”按钮时自行关闭。

我是否在代码中遗漏了一些东西,这些东西会在我们单击“打开”或“取消”按钮时关闭对话框?
谁能帮帮我吗?

最佳答案

您正在 UI 的 Application Thread 上长时间运行不应该这样做,否则 UI 将变得无响应。

而是创建一个TaskThread应用程序线程上执行长时间运行的进程。

参见this有关 JavaFX 中并发性的更多信息的链接

这是一个任务的简短示例:

import javafx.concurrent.Task;

....

FileChooser fc = new FileChooser();
fc.setTitle("Pointel File");
File file1 = fc.showOpenDialog(MainFrame.objComponent.getPrimaryStage());

    final Task task = new Task<Void>() {
        @Override
        protected Void call() throws Exception {
            int i = 0;
            while (i < 90000) {
                System.out.println(i);
                i++;
            }
            return null;
        }
    };
    Thread th = new Thread(task);
    th.setDaemon(true);
    th.start();

另请记住,如果您修改任何 JavaFX UI 组件,请将代码包装在 Platform.runLater(Runnable r) 中像这样的 block :

import javafx.concurrent.Task;

....

final Task task = new Task<Void>() {
    @Override
    protected Void call() throws Exception {
        int i = 0;
        while (i < 90000) {
            System.out.println(i);
            i++;
        }
    Platform.runLater(new Runnable() {//updates ui on application thread
            @Override
            public void run() {
                //put any updates to ui here dont run the long running code in this block or the same will happen as doing a long running task on app thread
            }
        });
        return null;
    }
};
Thread th = new Thread(task);
th.setDaemon(true);
th.start();

关于java - 文件选择器对话框未关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13838089/

相关文章:

java - hibernate中表的位置

java - 应该覆盖哪个异常方法?

java - 当我运行不同的线程 javafx 时游戏卡住

select - JavaFX 2中的组合框选择项

java - 移动圆圈随机消失(javafx)

java - 使用默认实现的空安全映射比较器

java - 当一个线程失败时停止 ExecutorService 线程。 & 返回异常

multithreading - 如何避免不在 FX 应用线程上; currentThread = JavaFX 应用程序线程错误?

java - ClassNotFoundException : javax. annotation.Generated with JDK 11

multithreading - 使用 javafx.concurrent 的 JavaFX 网络后台任务