How can a KeyListener detect key combinations (e.g., ALT + 1 + 1)

前端 未结 6 1374
悲哀的现实
悲哀的现实 2020-11-27 07:02

How can I let my custom KeyListener listen for combinations of ALT (or CTRL for that matter) + more than one other key?

Assume

6条回答
  •  猫巷女王i
    2020-11-27 07:33

    ALT + 1 + 0 (or "ALT+10" as it could be described in a Help file or similar)

    seems to clash with (from one of your comments):

    So for example if the user wants to change data in column 11 (which would be called "10"), s/he'd press ALT + 1 + [lets go of both ALT and 1] 0.

    Assuming that ALT+10 means 'Pressing ALT, pressing and releasing 1, pressing and releasing 0, releasing ALT' I propose trying this:

    In keyPressed, listening for the ALT key, activate a boolean flag, isAltPressed, and create a buffer to hold key presses that occur (a string, say). In keyTyped, if isAltPressed is active, append key codes to the buffer. In keyReleased, listening for ALT again, open a conditional querying the buffer and executing actions.

        public void keyPressed (KeyEvent e){
            if (e.getKeyCode() == KeyEvent.VK_ALT){
            buffer = ""; //declared globally
            isAltPressed = true; } //declared globally
        }
    
        public void keyTyped (KeyEvent e){
            if (isAltPressed)
                buffer.append (e.getKeyChar());
        }
    
        public void keyReleased (KeyEvent e){
            if (e.getKeyCode() == KeyEvent.VK_ALT){
                isAltPressed = false;
                if (buffer.equals (4948)) //for pressing "1" and then "0"
                    doAction();
                else if (buffer.equals(...))
                    doOtherAction();
                ...
            }//if alt
        }
    

提交回复
热议问题