简体   繁体   English

按下 shift 键时更改鼠标光标

[英]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;我有一个JPanel的子类PointPanel ,我想在其中实现以下行为:如果鼠标悬停在实例上并按下 shift 键,则鼠标光标变为手形光标; if the shift key is released, the mouse cursor changes back to the default cursor.如果释放 shift 键,鼠标光标会变回默认光标。

In order to achieve this, I tried to add a KeyListener in the constructor:为了实现这一点,我尝试在构造函数中添加一个KeyListener

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?我想念什么?

I found it confusing when creating the KeyStroke.创建 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM