简体   繁体   English

如何在Java AWT和/或Swing中更改光标图像?

[英]How to change the cursor image in Java AWT and/or Swing?

I'm making a simple graphics editor (ie 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. 我没有计划任何花哨的东西,但我确实希望我的程序在进入Paint Panel时将鼠标光标更改为“+”或“O”之类的东西。 like in Photoshop or GIMP. 就像在Photoshop或GIMP中一样。 Gimp Cursor

How would I do this? 我该怎么做? I can't find anything in AWT / Swing threads on how to change the mouse cursor. 关于如何更改鼠标光标,我在AWT / Swing线程中找不到任何内容。

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. 以防有人想要比任何默认游标更“花哨”的东西:可以创建一个自定义光标(如果Toolkit支持它),显示任意自定义图像。 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");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM