您需要检查用户按下的键并防止处理无效键。我通过继承 IntegerBox 并使用 KeyDownHandler 来验证适当的情况来完成此操作。这是完整的课程。
public class IntegerTextBox extends IntegerBox {
public IntegerTextBox() {
super();
}
public void initialize() {
addKeyDownHandler(new KeyDownHandler() {
public void onKeyDown(KeyDownEvent event) {
int keyCode = event.getNativeKeyCode();
if (event.isAnyModifierKeyDown())
cancelKey();
switch (keyCode) {
case KeyCodes.KEY_LEFT:
case KeyCodes.KEY_RIGHT:
case KeyCodes.KEY_DELETE:
case KeyCodes.KEY_BACKSPACE:
case KeyCodes.KEY_ENTER:
case KeyCodes.KEY_ESCAPE:
case KeyCodes.KEY_TAB:
return;
}
String parsedInput = parseNumberKey(keyCode);
if (parsedInput.length() > 0) {
return;
}
else {
cancelKey();
}
}
});
}
/**
* Varifies that the key pressed is either a number key or a numeric pad key. Converts numeric pad keys to the string
* representation of their number values.
*
* @param keyCode - the key code.
* @return the key's number representation as a string.
*/
@SuppressWarnings("nls")
private String parseNumberKey(int keyCode) {
String result = new String();
switch (keyCode) {
case KeyCodes.KEY_ZERO:
case KeyCodes.KEY_ONE:
case KeyCodes.KEY_TWO:
case KeyCodes.KEY_THREE:
case KeyCodes.KEY_FOUR:
case KeyCodes.KEY_FIVE:
case KeyCodes.KEY_SIX:
case KeyCodes.KEY_SEVEN:
case KeyCodes.KEY_EIGHT:
case KeyCodes.KEY_NINE:
return result = String.valueOf((char) keyCode);
case KeyCodes.KEY_NUM_ZERO:
return result = "0";
case KeyCodes.KEY_NUM_ONE:
return result = "1";
case KeyCodes.KEY_NUM_TWO:
return result = "2";
case KeyCodes.KEY_NUM_THREE:
return result = "3";
case KeyCodes.KEY_NUM_FOUR:
return result = "4";
case KeyCodes.KEY_NUM_FIVE:
return result = "5";
case KeyCodes.KEY_NUM_SIX:
return result = "6";
case KeyCodes.KEY_NUM_SEVEN:
return result = "7";
case KeyCodes.KEY_NUM_EIGHT:
return result = "8";
case KeyCodes.KEY_NUM_NINE:
return result = "9";
}
return result;
}
}