Call getActionCommand with a KeyEvent

0

I have a GUI class and another Event Handler class that implements the Listeners. In the GUI I have 2 buttons that listen to the controller class.

How do I make the keyPressed method of the management class identify which JButton is being pushed? Is that in the actionPerformed method I do it with getActionCommand and setActionCommand in each button of the GUI, but it only works with mouse clicks, however I do not know how it is with keyboard events.

Greetings.

    
asked by Carlos Adrián Martínez Román 16.06.2018 в 06:30
source

1 answer

0

What you can do to identify which key is pressed is a switch where you compare the code of the key in the following way:

@Override
public void keyPressed(KeyEvent e) {
        switch(e.getKeyCode()){
            case KeyEvent.VK_UP:
                System.out.println("flecha de arriba");
            break;
            case KeyEvent.VK_DOWN:
                System.out.println("flecha de abajo");
                break;
            case KeyEvent.VK_RIGHT:
                System.out.println("flecha de la derecha");
                break;
            case KeyEvent.VK_LEFT:
                System.out.println("flecha de la izquierda");
                break;
                default:
                    System.out.println(e.getKeyCode());
                    break;
        }
    }

This is an example with the code of the arrows on the keyboard, if you want to obtain the one of a letter you can change the cases by one like this

case KeyEvent.VK_C

this is the case of the letter C for example, to do all this you must implement the keylistener interface

    
answered by 22.06.2018 в 03:11