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.HAND_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.setSize(500, 500);

            // Here we create a hand shaped cursor!
            Cursor cursor = new Cursor(Cursor.HAND_CURSOR);

Leave a Reply

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