How do I change the cursor shape in Swing?

Using the following code snippet 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’s objects (JLabel, JTextArea, JButton, etc) cursor using the setCursor() method. In the snippet below, for demonstration, we change the cursor of the JFrame. Your mouse pointer or cursor shape will be changed if you positioned inside the frame.

A collections of cursor shape 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.swing;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import java.awt.Cursor;

public class ChangeCursor extends JFrame {
    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> {
            ChangeCursor frame = new ChangeCursor();
            frame.setTitle("Change Cursor");
            frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            frame.setSize(500, 500);

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

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.