这是我的文件选择器对话框操作代码...
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 将变得无响应。
而是创建一个Task
或Thread
在应用程序线程上执行长时间运行的进程。
参见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/