GWT: handling more than one events on Label
I want handle events on a Label when user holds down some key (Ctrl) and then clicks the mouse button together (Ctrl + mouse click), like op开发者_StackOverflow中文版en some window etc... How could i do that in GWT? Should i get add two handlers or can do it with one?
thank you.
al
In your click handler you can check if the Ctrl key is pressed when the event was fired, see example below. You also might want to check for the specific mouse button the user clicked on. I've also added that to the example:
yourLabel.addClickHandler(new ClickHandler() {
if(NativeEvent.BUTTON_LEFT == event.getNativeButton() &&
event.isControlKeyDown()) {
//do what you want
}
});
Or for older version of GWT instead of event.isControlKeyDown
use event.getNativeEvent().getCtrlKey()
, which returns a boolean value true if the control key is pressed when this event is fired.
Edit: this code is buggy, please look at Hilbrand's answer
To be honest, I don't think you can do it with 1 or 2 handlers. I think you would need 3 handler.
- A KeyDownHandler that sets a boolean you can later read form the MouseDownHandler
- A MouseDownHandler that does what you want
A KeyUpHandler that resets the value of the boolean in the KeyDownHandler
boolean ctrlPressed; yourLabel.addDomHandler(new KeyDownHandler() { public void onKeyDown(KeyDownEvent event) { if(event.getAssociatedType().equals(KeyCodes.KEY_CTRL)) ctrlPressed=true; } }, KeyDownEvent.getType()); yourLabel.addDomHandler(new KeyUpHandler() { public void onKeyUp(KeyUpEvent event) { if(event.getAssociatedType().equals(KeyCodes.KEY_CTRL)) ctrlPressed=false; } }, KeyUpEvent.getType()); yourLabel.addClickHandler(new ClickHandler() { if(ctrlPressed) { //do what you want } });
精彩评论