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);
});
}
}
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024