问题描述
是否可以使用 Vaadin 处理 MouseDown/MouseUp 和 KeyDown/KeyUp 事件?我发现 论坛主题 有同样的问题,看起来答案是否定的,但那是 5 年前的事了——我希望以后的版本能有所改变.我仍然在 API 中找不到任何东西.也许有一些解决方法可以拦截此类事件?
Is it possible to handle MouseDown/MouseUp and KeyDown/KeyUp evens with Vaadin? I've found forum thread with the same question and looks like the answer is no, but it was 5 years ago - I hope something changed with later releases. Still I can't find anything in API. Maybe there's some workaround for intercepting such evens?
推荐答案
好吧,几天后我想出了可接受的(对我来说)解决方案.必需的组件必须用扩展拦截器包装(感谢@petey 在评论中的想法),里面有 KeyDownHandler
.但是诀窍不是添加到组件本身(因为它可能会错过触发),而是添加到 RootPanel
.所以这是一个有效的例子.
Well, after couple of days I came up with the acceptable (for me) solution. Required component has to be wrapped with extension-interceptor (credits to @petey for an idea in the comments) with KeyDownHandler
inside. But the trick is not to add to the component itself (because it can miss triggering), but to the RootPanel
. So here's a working example.
扩展:
public class InterceptorExtension extends AbstractExtension {
private boolean shiftKeyDown;
public InterceptorExtension(Tree tree) {
super.extend(tree);
registerRpc((InterceptorExtensionServerRpc) state -> shiftKeyDown = state);
}
public boolean isShiftKeyDown() {
return shiftKeyDown;
}
}
ServerRpc:
public interface InterceptorExtensionServerRpc extends ServerRpc {
void setShiftKeyDown(boolean state);
}
连接器:
@Connect(InterceptorExtension.class)
public class InterceptorExtensionConnector extends AbstractExtensionConnector {
@Override
protected void extend(final ServerConnector target) {
final InterceptorExtensionServerRpc rpcProxy = getRpcProxy(InterceptorTreeExtensionServerRpc.class);
final RootPanel rootPanel = RootPanel.get();
rootPanel.addDomHandler(new KeyDownHandler() {
@Override
public void onKeyDown(KeyDownEvent event) {
if (event.isShiftKeyDown()) {
rpcProxy.setShiftKeyDown(true);
}
}
}, KeyDownEvent.getType());
rootPanel.addDomHandler(new KeyUpHandler() {
@Override
public void onKeyUp(KeyUpEvent event) {
if (!event.isShiftKeyDown()) {
rpcProxy.setShiftKeyDown(false);
}
}
}, KeyUpEvent.getType());
}
}
然后,您可以随时通过 InterceptorExtension#isShiftKeyDown 在服务器端获得 Shift 按钮状态.
Then whenever you want you can get Shift-button state on the server-side via InterceptorExtension#isShiftKeyDown.
这篇关于Vaadin:MouseDown/MouseUp 和 KeyDown/KeyUp 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!