[SOLVED] Java2d Changing mouse cursor + capturing it

Hello guys, how are you?

I wanted to know how to change the mouse cursor to one self-made.
Also, to keep mouse inside the application, it’s enough to check cords with public void mouseMoved(MouseEvent arg0)? Or how it should be handled? I’d like to capture the mouse inside the game and force an “alt + tab” to give it back to windows (also, multi platform code will be great!).

Thanks! :slight_smile:

Edit: 4/4/12 - Changed title to Solved. The keeping it inside the game´s window is something that I have yet to work it out. If I run into any problem, I´ll come back here :slight_smile:

Custom cursors are very easy to use, see here. Use a MouseMotionListener to detect movement, use a Robot to reset the mouse to the center of the window each frame and use a FocusListener to grab and ungrab the mouse on alt-tab.

Heh, this is actually easier to do with LWJGL… Mouse.setGrabbed() and Mouse.setCursor(). xD

Resetting the mouse to the center works, but unfortunately it messes up OS cursor acceleration: when you move the mouse from A to B slowly, it moves the cursor less far on screen than when you move it from A to B quickly.

Resetting the mouse coordinates interferes with that logic. It might not be a problem in your game, but it certainly should not be ignored.

Thank you both!

@Riven: If it’s not a problem in my game (did you refer to AEI?) why I should not ignore it? Or better, how should I take care of it?

@theagentd: I WILL go to LWJGL in time, I just wanted to go trough the road of Java2d, Slick and LWJGL (in a 2d game) and later on, a 3d game :slight_smile:

Well, I tried what theagentd said but it didn’t work. The cursor turns invisible :frowning:

Here’s the code:


Toolkit toolkit = Toolkit.getDefaultToolkit();  
Image image = toolkit.getImage("sprites/others/cursor.png");  
Point hotSpot = new Point(0,0);  
Cursor cursor = toolkit.createCustomCursor(image, hotSpot, "Cursor");
frame.setCursor(cursor);

This piece of code is in the game’s engine where the JFrame and the canvas is created and handled, just before the “while(isRunning)” loop. Thanks :slight_smile:

Maybe the image isn’t found.

Don’t use toolkit.getImage. Use:


BufferedImage image = ImageIO.read(getClass().getClassLoader().getResource("path/from/root"));

ra4king, just take my money. :stuck_out_tongue:

That worked perfectly! Thanks mate :slight_smile:

Hahaha glad to help :slight_smile:

I changed the title to solved so this thread can rest in peace :slight_smile:

I wanted to leave this here for the records :slight_smile:

The custom cursor must be 32x32 pixels, otherwise it will be resized by the Toolkit. The best thing to do is make your it in a 32x32 image, put your custom cursor in the upper left of it, and set the rest transparent.