当有人按下某个键时,我正在使用KeyEventDispatcher进行捕获。
现在我正在使用开关打印消息:
public boolean dispatchKeyEvent( KeyEvent e ) {
if ( e.getID() == KeyEvent.KEY_PRESSED ){
switch ( e.getKeyChar() ) {
case '\n':
System.out.println( "Equals" );
break;
case '+':
System.out.println( "Addition" );
break;
case '-':
System.out.println( "Subtraction" );
break;
case '/':
System.out.println( "Division" );
break;
case '*':
System.out.println( "Multiplication" );
break;
case '1':
System.out.println( "1" );
break;
case '2':
System.out.println( "2" );
break;
case '3':
System.out.println( "3" );
break;
case '4':
System.out.println( "4" );
break;
case '5':
System.out.println( "5" );
break;
case '6':
System.out.println( "6" );
break;
case '7':
System.out.println( "7" );
break;
case '8':
System.out.println( "8" );
break;
case '9':
System.out.println( "9" );
break;
case 'c':
case '':
System.out.println( "Clear" );
break;
case 'a':
System.out.println( "Clear Everything" );
break;
default:
break;
我输出两条输出线。例如,当我按9时,输出如下:
9
9
当我介入时,会运行两次:
java.util.List<KeyEventDispatcher> dispatchers = getKeyEventDispatchers();
if (dispatchers != null) {
for (java.util.Iterator<KeyEventDispatcher> iter = dispatchers.iterator();
iter.hasNext(); )
{
if (iter.next().
dispatchKeyEvent(ke))
{
return true;
}
}
}
return dispatchKeyEvent(ke);
}
知道我做错了什么吗?如果我从if语句中取出switch语句,我会得到6条打印行。我无法理解!
答案 0 :(得分:2)
对于键盘上键入的每个物理键,将发生以下事件
您可能需要使用KEY_TYPED。另一种可能性是你已经两次注册了听众。