我正在尝试在Java中为JButton创建自定义游标。 所以我使用Toolkit类。 但是Toolkit方法无法以某种方式加载我的图像。这是我的代码:
public class ButtonPerso extends JButton{
private Toolkit toolkit;
private Cursor myCursor;
private Point hotSpot;
private Image image;
public ButtonPerso(String label) {
super(label);
Toolkit.getDefaultToolkit();
image = toolkit.createImage("candle.gif" );
hotSpot = new Point(0, 0);
//myCursor = toolkit.createCustomCursor(image, hotSpot, "Candle");
myCursor = toolkit.createCustomCursor(image, hotSpot, "Candle");
addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent e) {
//setCursor (Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
setCursor(myCursor);
}
}
);
}
}
每次我收到错误:
Exception in thread "main" java.lang.NullPointerException
at GUI.ButtonPerso.<init>(ButtonPerso.java:36)
at GUI.Menu.<init>(Menu.java:61)
at GUI.Fenetre.<init>(Fenetre.java:18)
at Main.main(Main.java:34)
所以我猜这些例外情况正在发生:IndexOutOfBoundsException,HeadlessException.
我试图找到问题所在:
try {
myCursor = toolkit.createCustomCursor(Menu.image, hotSpot, "Candle");
}
catch (HeadlessException h) {
}
catch (IndexOutOfBoundsException i) {
System.out.println("index except");
}
但我仍然得到同样的警告,我不知道该怎么办你能帮我一把吗?也许它来自我的形象
答案 0 :(得分:3)
而不是这一行:
Toolkit.getDefaultToolkit();
你想写:
toolkit = Toolkit.getDefaultToolkit();
否则toolkit
将保持null
,当您尝试在其上调用方法时,您将获得NullPointerException
。
答案 1 :(得分:1)
private Toolkit toolkit;
\\ toolkit is not initialized and hence it is a null reference.
\\ Below line will throw NullPointerException
image = toolkit.createImage("candle.gif" );
\\ You need to assign the toolkit first.
toolkit = Toolkit.getDefaultToolkit();