Problems using getKeyCode ()


I'm starting to schedule events in java and I have a problem with getKeyCode (). In a JFrame of my program I added this.addKeyListener(lamina1); (lamina1 is an instance of a class that inherits from JPanel) this is the listener code:

public void keyTyped(KeyEvent e) {

        chars.add(numcaracteres, true);
        char txt=e.getKeyChar();
        chars.add(numcaracteres, txt);




(chars is an instance of ArrayList) The problem I have is that if(e.getKeyCode()==KeyEvent.VK_ENTER) does not work, because when I press enter, it does not execute the code inside the if, I tried to change VK_ENTER for other values to check if it was only with enter, but the same thing happens with any other value

asked by Alejandro Arevalo 07.04.2017 в 02:52

1 answer


Use KeyBindings . KeyListener has 2 major deficiencies.

  • a) You hear all the keys
  • b) You have to have focus on the component and also that component has to be focusable.

In contrast to KeyBindings, it is binded by a key and you do not necessarily have to be in focus.

A simple example:

AbstractAction enterAction = new AbstractAction() {
    public void actionPerformed(ActionEvent e) {
         //code here example
 String key = "ENTER";
 KeyStroke keyStroke = KeyStroke.getKeyStroke(key);
 component.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, key);
 component.getActionMap().put(key, enterAction);

You can use these JComponent constants

answered by 07.04.2017 / 04:54