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.HAND_CURSOR
  • Cursor.WAIT_CURSOR
  • etc
package org.kodejava.example.swing;

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

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

            // 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.