user3462940
user3462940

Reputation: 59

Custom cursor in java

Recently I'm building a java swing application and want to add a custom cursor. I used the following code,

public void customCursor() {
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Image image = toolkit.getImage("pencil.gif");
    Point hotspot = new Point(0,0);
    Cursor cursor = toolkit.createCustomCursor(image, hotspot, "pencil");
    setCursor(cursor);
}

And call the customCursor() method inside constructor. When i run the application my cursor is invisible. I tried giving the absolute path and using a url also. Still the same problem. Also I got to know (as mentioned here http://en.allexperts.com/q/Java-1046/cursor-1.htm) that the best cursor size for windows OS is 32x32. So for the above code set i added the following line,

toolkit.getBestCursorSize(32, 32);

still no progress. Also i tried using a 32x32 pixel image, still bad luck. Can anybody suggest a solution. (in case of a version issue, i'm using jdk 1.7 and jre7)

Upvotes: 1

Views: 3403

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347184

The likely cause is going to be the location of the image.

From you code example, the image "seems" to be an embedded resource. These resources can't be accessed like normal files on the file system.

Instead of

 Image image = toolkit.getImage("pencil.gif");

Try using...

 Image image = toolkit.getImage(getClass().getResource("pencil.gif"));

assuming the image resides within the same location as the class file or

 Image image = toolkit.getImage(getClass().getResource("/pencil.gif"));

if the image resides somewhere else (this example demonstrates the image located in the default package).

Cursors

Upvotes: 3

Related Questions