我怎样才能在Vaadin中实现这一目标。
// inside myButton click event
myButton.setEnabled(false);
doMyActionThatTakeSomeTime();
myButton.setEnabled(true);
在事件内部,永远不会禁用该按钮,因为UI未刷新。
在Vaadin 11(或10)中这样做的最佳做法是什么?
编辑解决方案 - 如何使其与Thread一起使用
到目前为止,使用Thread(工作)的示例:
@Push
@Route(value = "secured")
public class MainView extends VerticalLayout
[ ... ]
// inside click event
UI ui = UI.getCurrent();
new Thread(() -> {
ui.access(() -> {
goButton.setEnabled(false);
ui.push();
});
doMyActionThatTakeSomeTime();
ui.access(() -> {
goButton.setEnabled(true);
ui.push();
});
}).start();
听起来像文档中的“异步更新”一章解释了你想要的:https://vaadin.com/docs/v11/flow/advanced/tutorial-push-access.html。基本上:在单独的后台线程中运行doMyActionThatTakeSomeTime()
,然后在线程完成后重新启用按钮,Server Push将确保UI状态正确更新。
这是经常被问到的主题,这里还有另一个答案:How to dismiss Vaadin 8 confirmation dialog while performing lengthy operation以类似的方式在Vaadin 8和Vaadin 10+中进行异步更新。
在Vaadin 8中,有一个用于此目的的Button::setDisableOnClick()
方法。
这也许应该在新版本中重新引入。
对我来说最简单的方法是:
Button btnAction = new Button("Action");
btnAction.setDisableOnClick(true);
btnAction.addClickListener(e -> {
try {
for (int i = 0; i < 900000; i++) {
System.out.println(i);
}
} finally {
btnAction.setEnabled(true);
}
});
更好的方法:
UI ui = UI.getCurrent();
ui.access( () -> {
// disable button
goButton.setEnabled(false);
ui.push();
doMyActionThatTakeSomeTime();
// enable
goButton.setEnabled(true);
ui.push();
});