I have a method where he performs another method depending on the button clicked. Only he seems to be running the methods called twice, and I do not know why. Can anyone help me and explain to me why this is? Follows the source
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
@Override
public void eventDispatched(final AWTEvent event) {
final KeyEvent evt = (KeyEvent) event;
switch (evt.getKeyCode()) {
case KeyEvent.VK_F1: {
//F1
doSomething(); // this method is running twice
break;
}
case KeyEvent.VK_F2: {
//F2
doSomething();
break;
}
}, AWTEvent.KEY_EVENT_MASK);
Thanks
The problem appears to be that both the key-press and key-released methods are triggering the event. I would recommend using java.awt.event.KeyListener
, which has separate event handlers for the press and release events.
You are receiving an event for KEY_PRESSED and KEY_RELEASED.
You need to check if, in addition to the KeyEvent
having the correct KeyCode you want to make sure it is the correct action, ie KEY_PRESSSED. One way to fix this is add a check for the action before you go into your switch statement.
Toolkit.getDefaultToolkit().addAWTEventListener(new AWTEventListener() {
@Override
public void eventDispatched(final AWTEvent event) {
if (event.getKeyChar() == KeyEvent.KEY_PRESSED)
{
final KeyEvent evt = (KeyEvent) event;
switch(event.getKeyCode()){
//switch statement code
}
}
}, AWTEvent.KEY_EVENT_MASK);
Another thing you could do is create a KeyEventDispatcher
and add it to the KeyboardFocusManager
like this:
//create KeyEventDispatcher myKeyEventDispatcher
KeyboardFocusManager focusManager = KeyboardFocusManager.
getCurrentKeyboardFocusManager();
focusManager.addKeyEventDispatcher(myKeyEventDispatcher);
That way you will only get key event and you can dispatch them yourself
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.