Java Swing GUI

How to create a custom cursor in Java

In this tutorial, we are going to see how to define your own custom image cursor for a swing component, using createCustomCursor() method in the Toolkit class which takes only three parameters, the Image object, the access point, and the cursor description.

You can find the right cursor for you on this link.


[st_adsense]  

How to create a custom cursor in Java
import javax.swing.*;
import java.awt.*;

class CustomCursor  extends JFrame
{   
    public CustomCursor()
    {
        showApp();
    }
  
    private void showApp()
    {
        setTitle("Custom cursor");
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new FlowLayout());
        add(new JButton("Click here !"));
        
        try
        {
             setCursor(
                  Toolkit
                  .getDefaultToolkit()
                  .createCustomCursor(
                         new ImageIcon("my-cursor.png").getImage(),
                         new Point(0,0),
                         "My cursor"
                  )
             );
        }catch(Exception e){}

        setSize(300, 300);
        setVisible(true);
    }
    
    public static void main(String args[])
    {
        SwingUtilities.invokeLater(new Runnable(){
            public void run()
            {
                new CustomCursor();
            }
        });
    }
}

Output:


[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

One thought on “How to create a custom cursor in Java

  • not showing arrow in JFrame .

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *