Reputation: 193
I am trying to create custom cursors for JButtons in Java. So I use the Toolkit class. However Toolkit methods somehow fail to load my image. Here is my code:
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);
}
}
);
}
}
Everytime I get this error:
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)
So I guess there is something happening with these exception: IndexOutOfBoundsException,HeadlessException.
I tried to locate the problem:
try {
myCursor = toolkit.createCustomCursor(Menu.image, hotSpot, "Candle");
}
catch (HeadlessException h) {
}
catch (IndexOutOfBoundsException i) {
System.out.println("index except");
}
But I still get the same warnings, I don't know what to do can you give me a hand ? Perhaps it comes from my image
Upvotes: 0
Views: 225
Reputation: 206926
Instead of this line:
Toolkit.getDefaultToolkit();
You'll want to write:
toolkit = Toolkit.getDefaultToolkit();
Otherwise toolkit
will remain null
, and you'll get a NullPointerException
when you try to call a method on it.
Upvotes: 3
Reputation: 49412
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();
Upvotes: 1