Search code examples
javakeyboardmouseeventkeyeventkeystroke

Function to check if keyispressed


I need to see if a modifier key is pressed(shift,ctrl,alt) for my mouse event(basically ctrl+click)

I was wondering if there is a simple function to check if a key is pressed without implementing a keylistner or action events so as to not have the hassle of keeping track of where the focus is or where the variables are.


Solution

  • You can get the mask of which modifiers were pressed by calling InputEvent.getModifiers().

    Thus if you want to know whether a particular modifier was pressed (e.g. Shift), you could do this as

    // (doesn't have to be a method, of course, you could easily do this inline)
    private boolean wasShiftPressed(MouseEvent evt) {
        return evt.getModifiers() & InputEvent.SHIFT_MASK != 0;
    }