如何在Java AWT和/或Swing中更改光标图像? [英] How to change the cursor image in Java AWT and/or Swing?
问题描述
我正在制作一个简单的图形编辑器(即绘图程序)。我不打算任何花哨,但我希望我的程序,当它进入绘画面板时,将鼠标光标更改为类似+或O。像在Photoshop或GIMP。
I'm making a simple graphics editor (i.e a paint program). I am not planning on anything fancy, but I do want my program to change the mouse cursor to something like a "+" or an "O" when it enters the Paint Panel. like in Photoshop or GIMP.
做这个?我在AWT / Swing线程中找不到任何有关如何更改鼠标光标的信息。
How would I do this? I can't find anything in AWT / Swing threads on how to change the mouse cursor.
推荐答案
比任何默认游标更奇怪:它可以创建一个自定义光标(如果工具包支持它)显示任意自定义图像。粗糙(无光泽的视觉效果)示例:
Just in case someone wants something more "fancy" than any of the default cursors: it's possible to create a custom cursor (provided the Toolkit supports it) showing an arbitrary custom image. A crude (no shiny visuals) example:
Toolkit kit = Toolkit.getDefaultToolkit();
Dimension dim = kit.getBestCursorSize(48, 48);
BufferedImage buffered = GraphicsUtilities.createCompatibleTranslucentImage(dim.width, dim.height);
Shape circle = new Ellipse2D.Float(0, 0, dim.width - 1, dim.height - 1);
Graphics2D g = buffered.createGraphics();
g.setColor(Color.BLUE);
g.draw(circle);
g.setColor(Color.RED);
int centerX = (dim.width - 1) /2;
int centerY = (dim.height - 1) / 2;
g.drawLine(centerX, 0, centerX, dim.height - 1);
g.drawLine(0, centerY, dim.height - 1, centerY);
g.dispose();
Cursor cursor = kit.createCustomCursor(buffered, new Point(centerX, centerY), "myCursor");
这篇关于如何在Java AWT和/或Swing中更改光标图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!