我在名为tree的类中创建了这个方法:
public void printTree(Graphics g, int x, int y) {
MediaTracker mt = new MediaTracker(this);
tree = getImage(getCodeBase(), "tree.png");
mt.addImage(tree, 0);
g.drawImage(tree, x, y, this);
我尝试在paint方法的main中使用它:
Tree tree = new Tree();
tree.printTree(g, 60, 50);
我没有错误,但是当我运行应用程序时,我得到了这些错误:
Exception in thread "AWT-EventQueue-1" java.lang.NullPointerException
at java.applet.Applet.getCodeBase(Unknown Source)
at Tree.printTree(Tree.java:12)
at Main.paint(Main.java:146)
at Main.update(Main.java:187)
at sun.awt.RepaintArea.updateComponent(Unknown Source)
at sun.awt.RepaintArea.paint(Unknown Source)
at sun.awt.windows.WComponentPeer.handleEvent(Unknown Source)
at java.awt.Component.dispatchEventImpl(Unknown Source)
at java.awt.Container.dispatchEventImpl(Unknown Source)
at java.awt.Component.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
at java.awt.EventQueue.access$000(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.awt.EventQueue$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.awt.EventQueue$2.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)
如果有人可以帮助我,我会很高兴。
答案 0 :(得分:1)
您尝试使用的对象为null。使用调试器并找出哪一个,并找出如何确保它不为null,或修复使其为null的错误。
答案 1 :(得分:1)
Applet在AppletContext中运行 是否由appletviewer提供 或浏览器页面。如果你跑了 来自主方法的applet或加载 将applet放入应用程序中 不是AppletContext和getCodeBase 将返回null。在这种情况下你可以 使用备用/其他图像加载 方法
使用另一种方式import a picture into an applet。
答案 2 :(得分:0)
“我没有错误,但是当我运行应用程序时,我得到了这些错误:”
您可能意味着没有编译错误。 NullPointerException是一个相当常见但严重的错误。您必须在使用它们之前初始化对象。