While searching and asking around for the solution of a similar problem I've found your question and also the answer to it. This is the code I use in my program and it works. Note that this method was designed to be called only once and calling it constantly might require optimization. Also I've learned AffineTransform today and might have made some mistakes(even though code works).
Basically I rotate an image, create a new image from it and set the new image as the cursor.
My "cursor.png" is in the data folder.
private void rotateCursor(double rotation) {
// Get the default toolkit
Toolkit toolkit = Toolkit.getDefaultToolkit();
// Load an image for the cursor
BufferedImage image = null;
try {
image = ImageIO.read(this.getClass().getResource("/data/cursor.png"));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
AffineTransform at = new AffineTransform();
// affineTransform applies the added transformations in the reverse order
// 3. translate it back to the center of the picture
at.translate(image.getWidth() / 2, image.getWidth() / 2);
at.rotate(rotation);//2- adds rotation to at (they are not degrees)
//1- translate the object so that you rotate it around the center
at.translate(-image.getWidth() / 2, -image.getHeight() / 2);
BufferedImage rotated = null; // creates new image that will be the transformed image
// makes this: at + image= rotated
AffineTransformOp affineTransformOp = new AffineTransformOp(at,
AffineTransformOp.TYPE_BILINEAR);
image2 = affineTransformOp.filter(image, rotated);
// Create the hotSpot for the cursor
Point hotSpot = new Point(10, 0); // click position of the cursor(ex: + shape's is middle)
Cursor cursor = toolkit.createCustomCursor(rotated, hotSpot, "cursor");
// Use the custom cursor
this.setCursor(cursor);
}
You can use window.getMousePosition().x;
and window.getMousePosition().y;
for getting mouse position if you are using a mouseListener.
You need to call rotateCursor()
method with the correct double. How to calculate the correct double is something I can't help you with.
I hope it helps.
I've learned these from these sources:
storing transformed BufferedImage in Java
http://www.codebeach.com/2008/02/using-custom-cursors-in-java.html
Rotating BufferedImage instances
http://stumpygames.wordpress.com/2012/07/22/particles-tutorial-foundation/ (this tutorial also has a mouse listener)