This program is a work-in-progress tic-tac-toe game, where I've only just made the buttons; at least, theoretically. I looked up "null pointer exception" before posting this, but still don't understand how it applies here. Help?
//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);
}
}
}
The Result:
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)