Is this your first time here? SwingWiki is a Java Swing Developer community site with an big archive of Swing-related usenet groups and mailing lists, but also tips, tricks and articles and book reviews written by your colleagues from around the world. If you came here through a search engine and did not find what you were looking for, make sure to check the wiki table of contents.

Custom Cursor shape

Here’s how to create a custom cursor shape from an image file:

Toolkit kit = Toolkit.getDefaultToolkit();
setCursor(kit.createCustomCursor(kit.getImage("image.png"),new Point(0, 0), "Cursor"));

It is also important to use1): Toolkit.getDefaultToolkit().getBestCursorSize(orig_width, orig_height) to find an appropriate image size for createCustomCursor.

The default behavior may be to resize the given image. Resized cursors don’t look good. The solution is to create an image buffer of the required size and draw your image into it:

        Dimension best_size = Toolkit.getDefaultToolkit().
            getBestCursorSize(orig_width, orig_height);
        if(best_size.width == orig_width && best_size.height == orig_height) {
            cursor_img = orig_img;
            hotspot = new Point(orig_hotspot_x, orig_hotspot_y);
        } else if(best_size.width >= orig_width && best_size.height >= orig_height) {
            // by default the image would be scaled, but it looks better
            // to just surround it with a transparent border
            BufferedImage scaled_img = createImage(best_size.width, best_size.height);
            scaled_img.getGraphics().drawImage(orig_img, 0, 0, null);
            cursor_img = scaled_img;
            hotspot = new Point(orig_hotspot_x, orig_hotspot_y);
        } else {
            // JRE 1.3 on Mac only supports 16x16 cursors.
            // Resizing an image doesn't work well, so just
            // return the default cursor.  Maybe in the future
            // we could include some 16x16 images to fall
            // back on.  Better yet, get everyone to use
            // JRE 1.4
            return new Cursor(Cursor.DEFAULT_CURSOR);
	return Toolkit.getDefaultToolkit().createCustomCursor(
                cursor_img, hotspot, cur_name);
1) Thanks to Dan Stahlke for this tip

Comments? Corrections? Contact us or Login to edit pages directly (registration is free and takes less than displaying a JLabel)
  howto/custom_cursor_shape.txt · Last modified: 2006/12/21 19:03 by (gojko)
Recent changes | RSS changes | Table of contents | News Archive | Terms And Conditions | Register | The Quest For Software++| Ruby Resources

Sedo - Buy and Sell Domain Names and Websites project info: Statistics for project etracker� web controlling instead of log file analysis