ApprenticeHacker
ApprenticeHacker

Reputation: 22031

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

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. Gimp Cursor

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

Upvotes: 3

Views: 6681

Answers (1)

kleopatra
kleopatra

Reputation: 51536

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

Upvotes: 9

Related Questions