您在 UI 的应用程序线程上运行了很长时间,这不应该这样做,否则 UI 将变得无响应。
而是在应用程序线程上创建Task
或Thread
执行长时间运行的进程。
有关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();