如何在不使用showAndWait的情况下等待JavaFX应用程序线程上的用户输入? [英] How to wait for user input on JavaFX application thread without using showAndWait?

查看:1298
本文介绍了如何在不使用showAndWait的情况下等待JavaFX应用程序线程上的用户输入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在JavaFX应用程序线程上暂停执行方法,并等到用户与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应用程序线程上的用户输入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆