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_CURSORCursor.HAND_CURSORCursor.CROSSHAIR_CURSORCursor.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);
});
}
}
Latest posts by Wayan (see all)
- How do I scale and paint an image in Swing? - December 1, 2026
- How do I arrange components using BorderLayout in Java Swing? - December 1, 2026
- How do I map a Java class to a database table? - November 30, 2026