Can we change the Cursor with Java Swing?

Java 8Object Oriented ProgrammingProgrammingSwing

Yes, we can change the default cursor representation in Java. Let us first create a button component −

JButton button = new JButton("Button with two borders");

Whenever user will keep the mouse cursor on the above button component, the cursor would change to hand cursor −

Cursor cursor = button.getCursor();
button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));

The following is an example to change the cursor −

Example

package my;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Container;
import java.awt.Cursor;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.border.Border;
import javax.swing.border.EtchedBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Demo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      Border raisedBorder = new EtchedBorder(EtchedBorder.RAISED);
      LineBorder lineBorder = new LineBorder(Color.red);
      TitledBorder titleBorder = new TitledBorder("Demo Title");
      Border border = BorderFactory.createCompoundBorder(lineBorder, titleBorder);
      JButton raisedButton = new JButton("Raised Border");
      raisedButton.setBorder(raisedBorder);
      JButton button = new JButton("Button with two borders");
      button.setBorder(border);
      Cursor cursor = button.getCursor();
      button.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
      Container contentPane = frame.getContentPane();
      contentPane.add(raisedButton,BorderLayout.WEST);
      contentPane.add(button,BorderLayout.EAST);
      frame.setSize(600, 300);
      frame.setVisible(true);
   }
}

Output

The output is as follows. When you will keep the cursor on the button with two borders, then hand cursor will be visible as shown below −

raja
Published on 31-May-2019 14:57:00
Advertisements