0

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.

2
  • I may be totally wrong here, but I recently had a discussion with another programmer who pointed out issues with Z-ordering when combining AWT and Swing. I don't know about the code behind this program, but perhaps that may have something to do with this? Oct 26, 2014 at 18:28
  • I haven't looked into that. I'll be sure to see if that might be causing my issue. Thanks!
    – Hayeb
    Oct 26, 2014 at 22:39

2 Answers 2

1

A couple of options to consider:

  1. How to Use Layered Panes
  2. How to Decorate Components Using the JLayer Class
1
  • I had looked at suggestion #1, but suggestion #2 might provide the functionality I need! Will definitely try.
    – Hayeb
    Oct 27, 2014 at 15:06
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.