Search code examples
javakey-bindings

Java KeyEvent JUST ALT


I want to be able to (in a JPanel - I'm using KeyBindings for arrow keys and ALT + KeyEvent.VK_lots_of_different_keys) press ALT (and only ALT) and know when it is pressed so I can drag the mouse around and stop it from performing other things that should not happen when alt is pressed.

Is there a KeyEvent for this or a work-around? (I have tried the various (4) ALT key masks, but those obviously don't work).

some code:

altPressed = false;

InputMap inMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
ActionMap actMap = getActionMap();

KeyStroke pressed = KeyStroke.getKeyStroke(KeyEvent.VK_ALT, 0, false);
KeyStroke released = KeyStroke.getKeyStroke(KeyEvent.VK_ALT, 0, true);

inMap.put(pressed, "alt" + "pressed");
inMap.put(released, "alt" + "released");

actMap.put("alt" + "pressed", new AbstractAction () {
    private static final long serialVersionUID = 1L;

    @Override
    public void actionPerformed(ActionEvent e) {
        altPressed = true;
    }
});

actMap.put("alt" + "released", new AbstractAction () {
    private static final long serialVersionUID = 1L;

    @Override
    public void actionPerformed(ActionEvent e) {
        altPressed = false;
    }
});

private class KeyListener implements ActionListener {//... yada yada yada ...
    @Override
        public void actionPerformed(ActionEvent e) {// check if keys are pressed and perform proper actions....
...
...
}

Timer timer = new Timer(100, new KeyListener());
timer.start();

Solution

  • If you trying to detect if the Alt button is pressed while clicking/dragging/etc. with the mouse, you can use the getModifiersEx() method of MouseEvent. The MouseEvent object will be sent to your listener in each of the methods of the MouseInputListener impelementation.