在搜索和询问类似问题的解决方案时,我找到了您的问题及其答案。这是我在程序中使用的代码,它可以工作。请注意,此方法设计为仅调用一次,并且不断调用它可能需要优化。我今天也学习了 AffineTransform 并且可能犯了一些错误(即使代码有效)。
基本上我旋转一个图像,从中创建一个新图像并将新图像设置为光标。我的“cursor.png”在数据文件夹中。
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);
}
如果您使用的是 mouseListener,则可以使用window.getMousePosition().x;
and来获取鼠标位置。window.getMousePosition().y;
您需要rotateCursor()
使用正确的双精度调用方法。如何计算正确的双倍是我无法帮助您的。
我希望它有所帮助。
我从这些来源中学到了这些:
在 Java 中存储转换后的 BufferedImage
http://www.codebeach.com/2008/02/using-custom-cursors-in-java.html
旋转 BufferedImage 实例
http://stumpygames.wordpress.com/2012/07/22/particles-tutorial-foundation/(本教程还有鼠标监听器)