Custom cursor in Java

By September 21, 2010 No Comments

For a variety of reasons (most likely to improve the basic look of an interface using Java’s AWT) you may want to customize the appearance of the cursor in a Java application. For this purpose you would need your own cursor image, and this image should work well when hovering on top of both dark and light backgrounds. A way to achieve this is by using a cursor whose shape is colored with a dark hue and outlined in a light hue, or colored with a light hue and outlined in a dark hue. This contrast will always ensure clear visibility. To see how this works you can easily look at your current default cursor and notice the effect on both types of backgrounds.

In order to achieve this using Java, you could do the following:

import java.awt.Point;
import java.awt.Toolkit;
import java.awt.Image;
import java.awt.Cursor;

Toolkit toolkit = Toolkit.getDefaultToolkit();  
Image image = toolkit.getImage(“Images/MyCursor.png”);   
Point hotSpot = new Point(20,15);
Cursor cursor = toolkit.createCustomCursor(image, hotSpot, “Pencil”);  

Make sure your image is saved in the right place (the default file path will in most cases be your project folder). Most image file formats supported would work well, but I chose .png because it allows me to use transparency, which lets me outline a dark cursor with a border glow that fades out linearly. 

Leave a Reply