无法在另一个班级中创建打印Methord并将其称为主班级

问题描述

|| 我在名为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方法中使用它:
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)
如果有人可以帮助我,我将非常高兴。     

解决方法

           Applet在AppletContext中运行   是否由appletviewer提供   或浏览器页面。如果您运行   从主要方法或加载小程序   小程序进入应用程序   没有AppletContext和getCodeBase   将返回null。在这种情况下,您可以   使用备用/其他图像加载   方法。 参考 使用另一种方法将图片导入小程序。     ,        您尝试使用的对象为null。使用调试器,找出哪一个,并确定如何确保它不为null,或者修复使它为null的错误。     ,        \“我没有收到任何错误,但是当我运行该应用程序时,出现了以下错误:\” 您可能表示没有编译器错误。 NullPointerException是一个相当普遍但严重的错误。使用对象之前,必须先对其进行初始化。