问题描述
我想暂停 JavaFX 应用程序线程上方法的执行,并等待用户与 UI 进行交互.重要的是不要冻结 UI.
I'd like to pause the execution of a method on the JavaFX application thread and wait until the user does interaction with the UI. It's important not to freeze the UI.
示例:
Button start = ...
Button resume = ...
start.setOnAction(evt -> {
System.out.println("starting");
start.setDisable(true);
System.out.println("please press resume button.");
pause();
System.out.println("done");
start.setDisable(false);
});
resume.setOnAction(evt -> resume());
我应该如何实现 pause()
和 resume()
方法?
事件处理程序的执行应等待 pause();
调用,直到用户按下 resume
按钮并调用 resume
方法.
How should I implement the pause()
and resume()
methods?
The execution of the event handler should wait at pause();
call until the user presses the resume
button and the resume
method is called.
推荐答案
您可以使用 Platform.enterNestedEventLoop
暂停事件处理程序的执行和 Platform.exitNestedEventLoop代码>
(自 JavaFX 9 起可用)恢复执行:
You can do so by using Platform.enterNestedEventLoop
to pause the execution of the event handler and Platform.exitNestedEventLoop
(available since JavaFX 9) to resume the execution:
private final Object PAUSE_KEY = new Object();
private void pause() {
Platform.enterNestedEventLoop(PAUSE_KEY);
}
private void resume() {
Platform.exitNestedEventLoop(PAUSE_KEY, null);
}
Platform.enterNestedEventLoop
在 Platform.exitNestedEventLoop
使用作为第一个参数传递的相同参数调用时返回.
Platform.enterNestedEventLoop
returns when Platform.exitNestedEventLoop
is called with the same parameter passed as first argument.
这篇关于如何在不使用 showAndWait 的情况下等待 JavaFX 应用程序线程上的用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!