我试图通过Java图形程序制作一个简单的四个井字棋盘图像。 我的程序编译并可以运行,但不会生成四个板的图像。我在交互窗格中出现此错误(我使用DrJava进行编码):
Welcome to DrJava. Working directory is C:\Users\Daniel\Desktop\CS Programs
> run TicTacToeBoards
java.lang.NullPointerException
at TicTacToeBoards.drawTicTacToeBoard(TicTacToeBoards.java:38)
at TicTacToeBoards.<init>(TicTacToeBoards.java:18)
at TicTacToeBoards.main(TicTacToeBoards.java:52)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)
这是我试图运行的程序:
import java.awt.Color;
public class TicTacToeBoards {
private NsccWindow win;
public TicTacToeBoards() {
NsccWindow win;
win = new NsccWindow(10, 10, 330, 300);
win.setTitle("Tic-Tac-Toe Boards");
drawTicTacToeBoard(40, 40);
drawTicTacToeBoard(40, 170);
drawTicTacToeBoard(170, 40);
drawTicTacToeBoard(170, 170);
}
public void drawTicTacToeBoard(int x, int y) {
NsccLine vertLineL;
NsccLine vertLineR;
NsccLine horizLineU;
NsccLine horizLineD;
vertLineL = new NsccLine((x + 30), y, (x + 30), (y + 90));
vertLineR = new NsccLine((x + 60), y, (x + 60), (y + 90));
horizLineU = new NsccLine(x, (y + 30), (x + 90), (y + 30));
horizLineD = new NsccLine(x, (y + 60), (x + 90), (y + 30));
win.add(vertLineL);
win.add(vertLineR);
win.add(horizLineU);
win.add(horizLineD);
win.repaint();
}
public static void main(String[] args) {
TicTacToeBoards test = new
TicTacToeBoards();
}
}
我是Java编程的新手,我一直试图通过DrJava中的调试找到错误,但没有用。有人可以帮忙吗? :)
答案 0 :(得分:7)
从构造函数中删除此行:
NsccWindow win;
您已经拥有win
字段,因此无需在构造函数中声明它。
在构造函数中声明它时,隐藏实例字段并实例化仅限于构造函数范围的变量。因此,当您尝试访问drawTicTacToeBoard
中的实例字段时,实际上是null
。