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.DEFAULT_CURSOR
Cursor.HAND_CURSOR
Cursor.CROSSHAIR_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.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(250, 250);
// 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 install Calibri font in Ubuntu? - January 24, 2021
- How do I create a generic class in Java? - January 1, 2021
- How do I convert java.util.TimeZone to java.time.ZoneId? - April 25, 2020