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

Jes*_*ssy 44 java swing cursor

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

coo*_*ird 66

看起来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);
Run Code Online (Sandbox Code Playgroud)

编辑

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

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

JPanel p = ...
// Sets the JPanel's cursor to the system default.
p.setCursor(Cursor.getDefaultCursor());
Run Code Online (Sandbox Code Playgroud)


vax*_*uis 6

tl;博士 AWT工具包仍然在2017年被窃听'; 因此,适当的解决方案是打电话

  w.setCursor( w.getToolkit().createCustomCursor(
                   new BufferedImage( 1, 1, BufferedImage.TYPE_INT_ARGB ),
                   new Point(),
                   null ) );
Run Code Online (Sandbox Code Playgroud)

代替.


根据Javadoc页面createCustomCursor,

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

它将遵循这一点

w.setCursor( w.getToolkit().createCustomCursor( null, null, null ) );
Run Code Online (Sandbox Code Playgroud)

应该做的伎俩.遗憾的是,有一个与此案例相关的错误未由代码处理,请参阅http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=7150089(这个特别适用于MacOS,但是通过浏览源代码你可以很容易地发现,有一个为1 PARAM没有检查Image中值有效性任何的的Toolkit平台实现,有tracker.isErrorAny()检查,不这样做是在这种情况下工作),所以传递null或无效Image只是抛出一个NPEx.