ADS

How To Set Custom Image Cursor In Java?

Image of a cursor that is set to a swing component How to set custom image cursor in Java?
Since time, it was my tiny dream to set my own custom image cursor for a swing component and now I am able to do that in a single line! What have I done is I have been searching for a method in the Cursor class so was unable to find. I asked myself how did I forget the Toolkit class that has createCustomCursor() which takes just three parameters, the Image object, hotspot point and cursor description. Fine, let us stop talking about this, and see the program.

 public Cursor createCustomCursor(Image cursor,Point hotspot,String desc) throws IndexOutOfBoundsException, HeadlessException

 import javax.swing.*;
import java.awt.*;
class CustomImageCursor extends JFrame
{
    public CustomImageCursor()
    {
        createAndShowGUI();
    }
   
    private void createAndShowGUI()
    {
        setTitle("Image Cursor");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
       
        add(new JButton("Button"));
        add(new JCheckBox("Checkbox"));
       
        try
        {
        setCursor(Toolkit.getDefaultToolkit().createCustomCursor(new ImageIcon("mycursor1.png").getImage(),new Point(0,0),"custom cursor"));
        }catch(Exception e){}
       
        setSize(400,400);
        setVisible(true);
    }
   
    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
                new CustomImageCursor();
            }
        });
    }
}

References:

  1. java.awt.Toolkit - Java SE 7
  2. java.awt.Cursor - Java SE 7
If you love the way a custom cursor is set, please share it.

Subscribe to receive free email updates:

ADS