如何在 Swing 应用程序中隐藏光标?

新手上路,请多包涵

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

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

原文由 Jessy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 704
2 个回答

似乎 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 中包含的 JFrame 继承游标将结束的容器( JFrame ),所以如果需要有一个特定的 Component 有光标出现,则必须手动设置所需的光标。

For example, if there is a JPanel contained in the JFrame , then one could set the cursor of that JPanel to the system’s default using the Cursor.getDefaultCursor 方法:

 JPanel p = ...
// Sets the JPanel's cursor to the system default.
p.setCursor(Cursor.getDefaultCursor());

原文由 coobird 发布,翻译遵循 CC BY-SA 2.5 许可协议

tl;dr AWT 工具包在 2017 年仍然存在问题’;因此,正确的解决方案是调用

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

反而。


根据 createCustomCursor 的 Javadoc 页面

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

由此可知

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

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

原文由 user719662 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题