Java Swing Custom Cursor is invisible

冷暖自知 提交于 2019-12-13 02:27:02

问题


I made a custom cursor using this tutorial. Problem is, as soon as it changes, i just get nothing. The cursor is invisible. I tried the pencil image given there, a custom image i quickly have drawn in paint, but they all don't work.

    public Cursor stoneCursor;
    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Image image = toolkit.getImage("pencil.gif");
    Point hotspot = new Point(0,0);
    stoneCursor = toolkit.createCustomCursor(image, hotspot, "Stone");
    getContentPane().setCursor(stoneCursor);

This is inside a JFrame ofcourse.

". If the image to display is invalid, the cursor will be hidden (made completely transparent), and the hotspot will be set to (0, 0)." This is written in the javadoc of createCustomCursor(), but it should work with the pencil.gif?

Thanks for the answers in advance! :)


回答1:


Your code works for me. I am betting that the toolkit can't find your image and therefore is unable to display it. Here is a complete working example that uses the same code as yours (except I used a public Image from a URL):

import java.awt.Cursor;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.net.MalformedURLException;
import java.net.URL;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class TestCursor {

    protected void initUI() throws MalformedURLException {
        JFrame frame = new JFrame("Test text pane");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Image image = toolkit.getImage(new URL("http://fc03.deviantart.net/fs71/f/2010/094/7/9/Kalyan_hand_cursor_1_by_Zanten.png"));
        Point hotspot = new Point(0, 0);
        Cursor cursor = toolkit.createCustomCursor(image, hotspot, "Stone");
        frame.setCursor(cursor);

        frame.setSize(600, 400);
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                try {
                    new TestCursor().initUI();
                } catch (MalformedURLException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
    }
}



回答2:


If you are using Java 1.5, this SO question might be interesting to you. If you use something newer, this code works perfectly for me as well (just tried it). If the image is not there or can not be accessed correctly, then I experience the same effect as you.

Make sure that the image is loaded correctly.



来源:https://stackoverflow.com/questions/11310404/java-swing-custom-cursor-is-invisible

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!