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.*;
import java.awt.*;

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

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

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you ?

Leave a Reply

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