我想处理一起按下的键组合( CTRL + ENTER )。
我试过这样做......
if ((event.getCharCode() == KeyCodes.KEY_ENTER)
&& event.isControlKeyDown()) {
//do smth...
}
......但它不起作用。我也试图看到这个组合的代码,它显示10.所以我可能会做event.getCharCode() == 10
但我认为这不是很好的做法,特别是因为API中有这样的方法{{1 }} 和别的。捕获组合键的适当方法是什么?
答案 0 :(得分:3)
尽管我写了你的问题的评论,但似乎要处理的更好的事件是KeyUpEvent
。在这种情况下,您可以获得正确的KeyCode
并测试修饰符。同样的情况适用于KeyDownEvent
,但是,当用户按住 CTRL 键时,您将获得多个KeyDownEvents
等待他们按 ENTER key,而应该只有一个KeyUpEvent
。
此解决方案似乎比charCode() == 10
中的KeyPressEvent
测试更具跨浏览器兼容性。对于 CRTL + ENTER ,Firefox似乎没有将charCode设置为10.
以下是我在Chrome,IE8和FF8中测试的一些代码:
package com.test.gwt.client;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.event.dom.client.KeyPressHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.i18n.client.NumberFormat;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.TextBox;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class GwtTest implements EntryPoint {
private TextArea messages;
/**
* This is the entry point method.
*/
public void onModuleLoad() {
// Add the textbox to receive events and a place to write messages
final TextBox nameField = new TextBox();
nameField.setText("");
messages = new TextArea();
messages.setText("");
RootPanel.get().add(nameField);
RootPanel.get().add(messages);
messages.setSize("75%", "400px");
// Focus the cursor on the name field when the app loads
nameField.setFocus(true);
nameField.addKeyUpHandler(new KeyUpHandler() {
@Override
public void onKeyUp(KeyUpEvent event) {
printMessage("KeyUpEvent",
event.getNativeKeyCode(),
event.isAnyModifierKeyDown(),
event.isControlKeyDown());
}
});
nameField.addKeyPressHandler(new KeyPressHandler() {
@Override
public void onKeyPress(KeyPressEvent event) {
printMessage( "KeyPressEvent",
event.getCharCode(),
event.isAnyModifierKeyDown(),
event.isControlKeyDown());
}
});
nameField.addKeyDownHandler(new KeyDownHandler() {
@Override
public void onKeyDown(KeyDownEvent event) {
printMessage( "KeyDownEvent",
event.getNativeKeyCode(),
event.isAnyModifierKeyDown(),
event.isControlKeyDown() );
}
});
}
public void printMessage(String eventName, int code, boolean modifier, boolean control) {
final NumberFormat formatter = NumberFormat.getDecimalFormat();
String message = eventName + " - Char Code: " + formatter.format(code) + ". ";
if(code == KeyCodes.KEY_ENTER) {
message += "Key is ENTER. ";
}
if(modifier)
message += "Modifier is down. ";
if(control)
message += "CTRL is down. ";
messages.setText(messages.getText() + "\n\n" + message );
}
}
答案 1 :(得分:0)
kgdboc=ttyAMA0,115200