简体   繁体   English

Java中的自定义鼠标光标绘图(摆动)

[英]Custom mouse cursor drawing in Java (swing)

I'm looking to create a custom mouse cursor for a drawing app in Java. 我正在为Java中的绘图应用程序创建自定义鼠标光标。 The app needs to be able to run on Windows and due to the restrictions in windows with relation to the size of the cursor (32 * 32 px) it is impossible to use the build-in Cursor functionality. 该应用程序必须能够在Windows上运行,并且由于Windows中与游标大小(32 * 32 px)有关的限制,因此无法使用内置的Cursor功能。

I have tried to draw an image at the current mouse location using a MouseMotionListener, and this works when I draw it on an empty panel. 我试图使用MouseMotionListener在当前鼠标位置绘制图像,并且在空面板上绘制时可以使用。 The image correctly 'follows' the mouse so that's not the problem. 该图像正确地“跟随”了鼠标,所以这不是问题。

@Override 
public void paintComponent(Graphics g) {        
    super.paintComponent(g);
    g.drawImage(cursorimage, x, y, null);
}

However, when I add children to this panel, the mouse cursor is displayed behind the children. 但是,当我将孩子添加到该面板时,鼠标光标显示在孩子后面。 For example, when I add a few buttons the mouse displays its image behind the buttons. 例如,当我添加一些按钮时,鼠标会在按钮后面显示其图像。 How can I move the cursor image to the foreground? 如何将光标图像移至前景?

I have tried a few things like changing the order in paintComponent: 我尝试了一些操作,例如更改paintComponent的顺序:

@Override 
public void paintComponent(Graphics g) {        
    g.drawImage(cursorimage, x, y, null);
    super.paintComponent(g);
}

I have also tried overriding other paint methods like paintChildren, paintComponents or even the paint method itself, but that didn't seem to work either. 我也尝试覆盖其他绘画方法,例如paintChildren,paintComponents甚至是paint方法本身,但似乎也没有用。 One of the children of the panel also has a drawComponent method overridden, and I suspect this has influence as well. 面板的子级之一也有一个drawComponent方法被覆盖,我怀疑这也有影响。

You need to paint in the glass pane. 您需要在玻璃窗格中绘画。 See the Java tutorial at http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html with source code at http://docs.oracle.com/javase/tutorial/uiswing/examples/components/GlassPaneDemoProject/src/components/GlassPaneDemo.java If you modify that source code so the mouseMoved method calls redispatchMouseEvent(e, true); 见在Java教程http://docs.oracle.com/javase/tutorial/uiswing/components/rootpane.html的源代码在http://docs.oracle.com/javase/tutorial/uiswing/examples/components/ GlassPaneDemoProject / src / components / GlassPaneDemo.java如果您修改该源代码,则mouseMoved方法将调用redispatchMouseEvent(e,true) ;。 the red dot will act like a cursor. 红点将充当光标。

Unfortunately I found that this doesn't work on Macs running Java 1.6, but it works on Macs running Java 1.8 and on Windows. 不幸的是,我发现这不适用于运行Java 1.6的Mac,但适用于运行Java 1.8的Mac和Windows。

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

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