我在一个名为树的类中创建了这个方法:
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);
我尝试在绘制方法的 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)
如果有人能帮助我,我会很高兴。
最佳答案
Applets run in an AppletContext whether provided by the appletviewer or a browser page. If you run an applet from a main method or load the applet into an application there will be no AppletContext and getCodeBase will return null. In this case you can use an alternate/other image loading method.
使用另一种方式import a picture into an applet .
关于java - 无法在另一个类中创建打印方法并在主类中调用它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6347351/