Reputation: 3
I'm looking to create a custom mouse cursor for a drawing app in 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.
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. 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:
@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. One of the children of the panel also has a drawComponent method overridden, and I suspect this has influence as well.
Upvotes: 0
Views: 1716
Reputation: 21
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); 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.
Upvotes: 0