该程序是一个进行中的井字游戏,我只做过按钮;至少在理论上。在发布此消息之前,我查找了“空指针异常”,但仍然不了解它在这里的应用方式。帮助?
//this line is line four
public class TicTacToe extends JFrame {
public static void main(String[] args) {
new TicTacToe();
}
public TicTacToe(){
super.setTitle("Tic Tac Toe");
super.setSize(800, 800);
super.setDefaultCloseOperation(EXIT_ON_CLOSE);
buildPanel();
super.setVisible(true);
}
public void buildPanel(){
GridLayout g = new GridLayout(3,3);
JPanel p = new JPanel();
p.setLayout(g);
JButton [] buttons = new JButton[9];
//I'm adding text temporarily to help me see where each button's position
buttons[0] = new JButton("One");
p.add(buttons[0]);
buttons[1] = new JButton("Two");
p.add(buttons[1]);
buttons[2] = new JButton("Three");
p.add(buttons[2]);
buttons[3] = new JButton("Four");
p.add(buttons[3]);
buttons[4] = new JButton("Five");
p.add(buttons[4]);
buttons[5] = new JButton("Six");
p.add(buttons[5]);
buttons[6] = new JButton("Seven");
p.add(buttons[6]);
buttons[7] = new JButton("Eight");
p.add(buttons[8]);
buttons[8] = new JButton("Nine");
p.add(buttons[8]);
add(p);
ActionListener Callback = event -> {
String label = event.getActionCommand();
};
for (int i=0;i<buttons.length;i++){
String string="O";
if (i%2==0){
string = "X";
}
buttons[i].setText(string);
buttons[i].addActionListener(Callback);
}
}
}
结果:
Exception in thread "main" java.lang.NullPointerException
at java.desktop/java.awt.Container.addImpl(Container.java:1117)
at java.desktop/java.awt.Container.add(Container.java:436)
at TicTacToe.buildPanel(TicTacToe.java:37)
at TicTacToe.<init>(TicTacToe.java:13)
at TicTacToe.main(TicTacToe.java:7)
这是问题:
buttons[7] = new JButton("Eight");
p.add(buttons[8]);
似乎是错字,我认为应该是
buttons[7] = new JButton("Eight");
p.add(buttons[7]);
在您的情况下,buttons[8]
尚未初始化(它将在异常之后的行中初始化),因此将导致NullPointerException
。