How do I change the cursor shape in Swing?

Using the following example you can change the shape of mouse cursor in your Java Swing desktop application. The cursor is represented by the java.awt.Cursor class. Create an instance of Cursor using the new operator and pass the cursor type to the Cursor class constructor.

We can change Swing objects (JLabel, JTextArea, JButton, etc) cursor using the setCursor() method. In the snippet below, for demonstration, we change the cursor of the JFrame. When your mouse pointer / cursor positioned inside the frame the shape will be changed.

A collections of cursor shapes defined in the java.awt.Cursor class, such as:

  • Cursor.DEFAULT_CURSOR
  • Cursor.HAND_CURSOR
  • Cursor.CROSSHAIR_CURSOR
  • Cursor.WAIT_CURSOR
  • etc
package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;

public class ChangeCursorDemo extends JFrame {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            ChangeCursorDemo frame = new ChangeCursorDemo();
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.setSize(250, 250);

            // Here we create a hand shaped cursor!
            Cursor cursor = new Cursor(Cursor.HAND_CURSOR);
            frame.setCursor(cursor);
            frame.setVisible(true);
        });
    }
}