51

有没有办法隐藏光标(除了使用透明图像作为光标)?

当用户将鼠标指向 JFrame 中的 JPanel 外部时,我想隐藏光标。

4

6 回答 6

79

似乎Cursor该类一开始就没有“空白”光标,因此可以使用该Toolkit.createCustomCursor方法定义一个新的“空白”光标。

这是我尝试过的一种似乎可行的方法:

// Transparent 16 x 16 pixel cursor image.
BufferedImage cursorImg = new BufferedImage(16, 16, BufferedImage.TYPE_INT_ARGB);

// Create a new blank cursor.
Cursor blankCursor = Toolkit.getDefaultToolkit().createCustomCursor(
    cursorImg, new Point(0, 0), "blank cursor");

// Set the blank cursor to the JFrame.
mainJFrame.getContentPane().setCursor(blankCursor);

编辑

关于JFrame最终没有光标的所有内容的注释,似乎Component包含在 s 中的 sJFrame最终会继承容器的光标(the JFrame),所以如果要求一定Component要有光标出现,必须手动设置所需的光标。

例如,如果 中JPanel包含a JFrame,则可以使用以下方法将其光标设置为JPanel系统默认值Cursor.getDefaultCursor

JPanel p = ...
// Sets the JPanel's cursor to the system default.
p.setCursor(Cursor.getDefaultCursor());
于 2009-12-31T05:55:08.260 回答
7

tl;dr AWT Toolkits 在 2017 年仍然存在错误;因此,正确的解决方案是调用

  w.setCursor( w.getToolkit().createCustomCursor(
                   new BufferedImage( 1, 1, BufferedImage.TYPE_INT_ARGB ),
                   new Point(),
                   null ) );

反而。


根据Javadoc 页面createCustomCursor

创建一个新的自定义光标对象。如果要显示的图像无效,光标将被隐藏(完全透明),热点将设置为 (0, 0)。

由此可知

w.setCursor( w.getToolkit().createCustomCursor( null, null, null ) );

应该做的伎俩。可悲的是,有一个与此案例相关的错误未由代码处理,请参见例如http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7150089(这特别适用于 MacOS,但通过浏览源代码您可能很容易发现在任何平台实现中都没有检查第一个参数值的有效性;有检查Image,在这种情况下它不起作用),所以通过或无效只会抛出一个 NPEx。Toolkittracker.isErrorAny()nullImage

于 2012-05-21T14:31:51.950 回答
3

在 Mac OS 下使用 LWJGL 时,您需要这样做:

System.setProperty("apple.awt.fullscreenhidecursor","true");
于 2011-10-12T00:10:13.230 回答
3
frame.setCursor(frame.getToolkit().createCustomCursor(
            new BufferedImage(3, 3, BufferedImage.TYPE_INT_ARGB), new Point(0, 0),
            "null"));
于 2011-11-21T13:30:09.330 回答
2

在文档中它说如果图像无效,则默认情况下它将是透明的,因此传递空图像将导致透明光标。但是null传入图像的方法会导致异常。

Toolkit tk= getToolkit();
Cursor transparent = tk.createCustomCursor(tk.getImage(""), new Point(), "trans");
于 2012-07-20T14:43:20.390 回答
1

我更容易解决这个问题:

final Timer cursorTimer = new Timer(2000, new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        getContentPane().setCursor(null);
    }
});
cursorTimer.start();

addMouseMotionListener(new MouseMotionAdapter() {
    @Override
    public void mouseMoved(MouseEvent e) {
        getGlassPane().setCursor(Cursor.getDefaultCursor());
        cursorTimer.restart();
    }
});
于 2010-11-30T17:12:00.720 回答