I saw a Web page whose cursor turned into a fish with five layers. Seeing this inspired me to change the cursor on my homepage
into a music note with three layers.
Can you help?
Java provides the functionality to create a custom cursor from any image. To do so, embed a Java applet with a changed cursor
in your HTML.
Creating the custom cursor is done through a method in java.awt.Toolkit API:
public Cursor createCustomCursor(Image cursor, Point hotSpot, String name)
throws IndexOutOfBoundsException
Toolkit is an abstract class, so first get the native implementation:
Toolkit tk = panel.getToolkit();
Then create the cursor:
Cursor cursor = tk.createCustomCursor(img, hotSpot, name);
Now, we can set the cursor on the panel:
panel.setCursor(cursor);
(The full applet source code is shown below.)
Unfortunately, custom cursors are available only in JDK 1.2 and higher. This means that most Web browsers will not support it, since most only go up to JDK 1.1. One alternative is to use the Java Plug-in for JDK 1.2, which works like any other browser plug-in. You can find more information at:
http://www.javasoft.com/products/plugin/index.html
Now, as promised, here's the full applet source code:
import java.awt.*;
import java.applet.*;
public class CursorApplet extends Applet {
public void init() {
//load the image with the Media Tracker
MediaTracker tracker = new MediaTracker(this);
Image cursor = getImage(getCodeBase(), "music_note.gif");
tracker.addImage(cursor, 0);
try {
tracker.waitForID(0);
} catch (InterruptedException ie) {
ie.printStackTrace();
}
Cursor cr = null;
//get the toolkit for this environment
Toolkit tk = getToolkit();
try
//this is the x,y coordinates of the image which
//will actually do the "clicking"
Point hotSpot = new Point(1, 1);
//create the custom cursor
cr = tk.createCustomCursor(cursor, hotSpot, "music_note");
} catch (IndexOutOfBoundsException e) {
e.printStackTrace();
}
//set the cursor for this applet component
setCursor(cr);
}
}