2

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

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”循环完成执行,而不是在我们单击“打开”按钮时自行关闭。

我是否遗漏了代码中的某些内容,当我们单击“打开”或“取消”按钮时会关闭对话框?
谁能帮帮我?

4

2 回答 2

2

您在 UI 的应用程序线程上运行了很长时间,这不应该这样做,否则 UI 将变得无响应。

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

有关JavaFX 中的并发的更多信息,请参阅此链接

这是一个简短的示例Task

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)块中,如下所示:

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();
于 2012-12-12T11:04:54.547 回答
0

Never do the GUI and the computational tasks on the same thread. Your UI should be running on one thread and your computational tasks should be on other threads. UI becomes unresponsive if they both are running on the same thread.

Firstly read about,

Threads

The Event Dispatch Thread

SwingWorker

Using the Event Dispatch Thread, you can dispatch your UI threads. Look at the answer given by @Erick Robertson related to EDT.

Many posts available in SO about the above stated topics.

于 2012-12-13T03:25:24.467 回答