Search code examples
javaswingkeyboardjtextfieldkeylistener

JTextfield should trigger all keyboard inputs


I want to trigger all keyboard inputs (also strg, alt and tab) in a JTextField.

super.addKeyListener(new KeyListener() {

    @Override
    public void keyTyped(KeyEvent arg0) {
        System.out.println(arg0.getKeyChar());
    }

    @Override
    public void keyReleased(KeyEvent arg0) {

    }

    @Override
    public void keyPressed(KeyEvent arg0) {

    }
});

KeyListener does not trigger keyboard inputs like strg, alt or / and tab.

Is there a solution for this case?

I need this for a settings screen, where the user can change the key, which must be pressed for a action like moving forward.


Solution

  • This works for me, I had to disable traversal in order to catch the Tab key. Also note that the keyTyped() event is never called for keys like Alt, Shift or Control. But you can catch them when you use the keyPressed() or keyReleased() events:

    public class Scribble extends JFrame implements KeyListener {
    
        public Scribble(){
            this.setLayout(new BorderLayout());
            JTextField field = new JTextField();
            field.addKeyListener(this);
            /*
             * Disable tab, so we can catch it
             */
            field.setFocusTraversalKeysEnabled(false);
            this.add(field, BorderLayout.CENTER);
            this.pack();
            this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            this.setLocationRelativeTo(null);
            this.setVisible(true);
        }
    
        public void keyTyped(KeyEvent e) {
            System.out.println("Key typed: " + e.getKeyCode());
        }
    
        public void keyPressed(KeyEvent e) {
            System.out.println("Key pressed: " + e.getKeyCode());
        }
    
        public void keyReleased(KeyEvent e) {
            System.out.println("Key released: " + e.getKeyCode());
        }
    
        public static void main(String[] args) {
            new Scribble();
        }
    }