How to wait for user input on JavaFX application thread without using showAndWait?

时光总嘲笑我的痴心妄想 提交于 2019-11-26 10:03:25

问题


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.

Example:

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());

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.


回答1:


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 returns when Platform.exitNestedEventLoop is called with the same parameter passed as first argument.




回答2:


I am currently running JFX 8 where I have the similar feature in the Toolkit class.

Toolkit.getToolkit().enterNestedEventLoop(obj);

and

Toolkit.getToolkit().exitNestedEventLoop(obj);

Have not looked at the JFX 9 source, but my bet is that the Platform methods are simply shortcuts to the same.



来源:https://stackoverflow.com/questions/46369046/how-to-wait-for-user-input-on-javafx-application-thread-without-using-showandwai

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!