Change Default Cursor to Hand Cursor in Java

In this tutorial, we will create a program that will change the default cursor into a hand cursor in java like the image below. hand cursor So, now let's start this tutorial! 1. Open JCreator or NetBeans and make a java program with a file name of jCursor.java. 2. Import java.io package. Hence the cursor class is in the input/output library. Import also javax.swing package because we will use JFrame and setCursor method here in the frame.
  1. import javax.swing.*;
  2. import java.awt.*;
3. In your class name make it sure it extends JFrame.
  1. public class jCursor extends JFrame {
4. Now, create a constructor that is the same with the file name.
  1. public jCursor() {
Create an instance of a Cursor class with a variable cursor and set it into Hand Cursor.
  1.      Cursor cursor = new Cursor(Cursor.HAND_CURSOR);
  2.      this.setCursor(cursor)
For window characteristics:
  1.         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  2.         this.pack();
5. In your Main, create a JFrame component that will hold all components. This will set the visibility to True, set the size, location, and has the title of the program.
  1.    public static void main(String[] args) {  
  2.         JFrame cur = new jCursor();
  3.         cur.setTitle("Hand Cursor");
  4.         cur.setVisible(true);
  5.         cur.setSize(300,250);
  6.         cur.setLocation(250,300);              
  7.     }
Press F5 to run the program. Full source code:
  1. import javax.swing.*;
  2. import java.awt.*;
  3.  
  4. public class jCursor extends JFrame {
  5.        
  6.         public jCursor() {
  7.                 Cursor cursor = new Cursor(Cursor.HAND_CURSOR);
  8.                  this.setCursor(cursor);
  9.  
  10.         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  11.         this.pack();
  12.      
  13.                
  14.         }
  15.        
  16.     public static void main(String[] args) {  
  17.         JFrame cur = new jCursor();
  18.         cur.setTitle("Hand Cursor");
  19.         cur.setVisible(true);
  20.         cur.setSize(300,250);
  21.         cur.setLocation(250,300);              
  22.     }
  23. }
Hope this helps! :) Best Regards, Engr. Lyndon Bermoy IT Instructor/System Developer/Android Developer/Freelance Programmer If you have some queries, feel free to contact the number or e-mail below. Mobile: 09488225971 Landline: 826-9296 E-mail:[email protected] Add and Follow me on Facebook: https://www.facebook.com/donzzsky Visit and like my page on Facebook at: https://www.facebook.com/BermzISware

Add new comment