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

China☆狼群 提交于 2019-12-10 20:22:06

问题


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.

How would I do this? I can't find anything in AWT / Swing threads on how to change the mouse cursor.


回答1:


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");


来源:https://stackoverflow.com/questions/8485241/how-to-change-the-cursor-image-in-java-awt-and-or-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!