Skip to content
Advertisement

Change the mouse cursor when shift key is pressed

I have a subclass PointPanel of JPanel, where I want to implement the following behavior: If the mouse hovers the instance and the shift key is pressed, the mouse cursor changes to the hand cursor; if the shift key is released, the mouse cursor changes back to the default cursor.

In order to achieve this, I tried to add a KeyListener in the constructor:

this.addKeyListener(new KeyAdapter() {
    @Override
    public void keyPressed(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
            System.out.println("Shift pressed");
            PointPanel.this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
        }
    }

    @Override
    public void keyReleased(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_SHIFT) {
            System.out.println("Shift released");
            PointPanel.this.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
        }
    }
});

This approach does not work.

The window which contains this panel should have the focus since it is the only visible window of the application.

What do I miss?

Advertisement

Answer

I found it confusing when creating the KeyStroke.

For the pressed I had to use:

KeyStroke pressed = KeyStroke.getKeyStroke("shift pressed SHIFT");

But for the released I could use either:

KeyStroke released = KeyStroke.getKeyStroke("released SHIFT");
KeyStroke released = KeyStroke.getKeyStroke(KeyEvent.VK_SHIFT, 0, true);

And I used:

InputMap im = getInputMap(JPanel.WHEN_IN_FOCUSED_WINDOW);
Advertisement