繁体   English   中英

关闭模式JComponent后,setCursor()出现问题

[英]Problem with setCursor() after closing modal JComponent

当我创建模式JComponent时,鼠标(正确)更改为默认光标。 但是,当我关闭组件时,我遇到了一个奇怪的问题。

  • 如果在光标处于组件边界内时关闭组件,则光标将正确还原。
  • 如果在光标超出范围的情况下关闭组件(例如,使用esc),即使调用setCursor(),光标也不会还原。

在这两种情况下,如何以非hacky的方式正确恢复光标?

示例代码:

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;

class ModalTest {
    public static void main (String[] args) {

        // Create a frame.
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setPreferredSize(new Dimension(800, 600));
        frame.pack();
        frame.setLocationRelativeTo(null);

        // Add a button.
        JButton button = new JButton();
        frame.add(button);
        frame.revalidate();
        frame.setVisible(true);

        frame.setCursor(Cursor.HAND_CURSOR);

        // While the mouse is inside the JFrame, the cursor should be Cursor.HAND_CURSOR.
        // And when the modal JOptionPane is visible, the cursor should be Cursor.DEFAULT_CURSOR.
        // However, when that modal JComponent is closed while the cursor is outside it, it does
        // not revert to Cursor.HAND_CURSOR.
        button.setAction(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent actionEvent) {
                JOptionPane.showConfirmDialog (
                    frame,
                    "Move the cursor inside, then outside of this component and press Esc. The cursor will stay default.",
                    "Cursor Test",
                    JOptionPane.YES_NO_OPTION
                );
                // Even if you change the cursor after, it stays default.
                frame.setCursor(Cursor.CROSSHAIR_CURSOR);
            }
        });
    }
}

暂无
暂无

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

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