0

我正在尝试为 Java 中的 JButtons 创建自定义光标。所以我使用 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");
  }

但我仍然收到同样的警告,我不知道该怎么办,你能帮帮我吗?也许它来自我的形象

4

2 回答 2

3

而不是这一行:

Toolkit.getDefaultToolkit();

你会想写:

toolkit = Toolkit.getDefaultToolkit();

否则toolkit会保留nullNullPointerException当你尝试调用它的方法时你会得到一个。

于 2013-05-31T12:00:15.997 回答
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();
于 2013-05-31T11:59:03.163 回答