Search code examples
javaswingkeylistenerkey-bindings

Can we implement KeyBindings using KeyListener?


Just the matter of interest, is there a way that KeyListener can do the same work as KeyBindings, I mean Overriding keyListener's method(s) and listen to multiple keys (CTRL+somekey).

I know, it's kinda stupid idea, but as I said, just a matter of interest.


Solution

  • You can do it by using a flag:

    KeyListener kl = new KeyListener() {
    
        boolean controlPressed = false;
        @Override
        public void keyTyped(KeyEvent e) {
        }
    
        @Override
        public void keyPressed(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_CONTROL) {
                controlPressed = true;
                return;
            }
    
            if(controlPressed) {
                // CTRL is pressed, you can check here for other keys:
                if(e.getKeyCode() == KeyEvent.VK_A) {
                    //CTRL + A was pressed
                }
            }
        }
    
        @Override
        public void keyReleased(KeyEvent e) {
            if(e.getKeyCode() == KeyEvent.VK_CONTROL) {
                controlPressed = false;
            }
        }
    };
    

    As camickr pointed out in comments, the other way would be to use the isControlDown method from KeyEvent:

    if(e.isControlDown()) {
        //CTRL is pressed
    }