Problems using getKeyCode ()

1

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) {

    if(e.getKeyCode()==KeyEvent.VK_ENTER){
        chars.add(numcaracteres, true);
    }else{
        char txt=e.getKeyChar();
        chars.add(numcaracteres, txt);
    }

    numcaracteres++;

    repaint();

}

(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
source

1 answer

2

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() {
    @Override
    public void actionPerformed(ActionEvent e) {
         //code here example
         ((JComponent)e.getSource()).setVisible(Boolean.FALSE);
    }};
 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

WHEN_ANCESTOR_OF_FOCUSED_COMPONENT 
WHEN_FOCUSED 
WHEN_IN_FOCUSED_WINDOW
    
answered by 07.04.2017 / 04:54
source