【问题标题】:Call an applet in another class method [duplicate]在另一个类方法中调用小程序[重复]
【发布时间】:2018-04-02 03:18:36
【问题描述】:

我正在制作图形计算器,因为我的计算机科学老师说,如果我能证明我知道课堂上将教授的所有主题,他将在今年剩下的时间里通过我,所以我的想法是图形计算器,而我正试图将我的 applet mumbo jumbo 放在不同的类中。但是在我觉得做事正确之后,我在尝试将我的类中的方法与小程序一起使用时出现错误。 这两个类都在同一个包中。 这是我打电话的班级: (我也已经导入了 java.awt.*)

public class NumberCalc {
//Bunch of variable for calculator
Graphics page;
static GraphingCalc graph = new GraphingCalc();

/* Blah blah calculator shit for miles
*  main method is in here with the drawGraph method
*
*/

public static void drawGraph() {
    graph.addPoint(20,20,5,5);
    //Test method to see if it draws, next class has the info
    }
}

这是我要调用的课程:

public class GraphingCalc {
Graphics page;
//Code that doesnt matter right now
public void addPoint(int x, int y, int sizeA, int sizeB) {
    setBackground(color.black);
    page.setColor(color.cyan) //Easy to see color for testing
    page.fillOval(x,y,sizeA,sizeB);
    }    
}

我得到的错误是这样的:

Exception in thread main java.lang.NullPointerException
at calculator.GraphingCalc.addPoint(GraphingCalc:18)

第 18 行是 page.setColor(color.cyan),如果我注释掉这一行并转到 fillOval,那么它会给出相同的错误,因此“page”图形变量显然有问题。有什么解决办法吗?

【问题讨论】:

标签: java nullpointerexception applet awt java-2d


【解决方案1】:

NullPointerException 表示您正在尝试引用一个没有值的变量。在这里,您有一个类型为 Graphics 和名称为 page 的字段的声明,但该字段从未初始化(至少在您发布的代码中没有)。换句话说 - 你试图询问pagesetColor(...),但没有page(因为你从未提供过它)。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2011-08-08
  • 2010-12-08
  • 2015-02-22
  • 2014-04-14
  • 1970-01-01
  • 1970-01-01
  • 2017-06-21
  • 1970-01-01
相关资源
最近更新 更多