我想暂停 JavaFX 应用程序线程上方法的执行,并等待用户与 UI 进行交互。重要的是不要卡住 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
方法被调用。
最佳答案
您可以使用 Platform.enterNestedEventLoop
来做到这一点。暂停事件处理程序的执行和 Platform.exitNestedEventLoop
(自 JavaFX 9 起可用)恢复执行:
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
使用作为第一个参数传递的相同参数调用。
关于javafx - 如何在不使用 showAndWait 的情况下等待 JavaFX 应用程序线程上的用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46369046/