I'm quite new to coding so please be kind!
I'm trying to code a tic tac toe game in Java Swing. But I'm having a quite annoying error and I don't understand why this error is being displayed. Can anyone help me understand why please?
this is my code :
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class Board extends JFrame {
private JPanel pan = new JPanel();
private boolean player1 = true;
private JButton[] tab_but = new JButton[9];
public Board() {
initializeComponent();
}
public void initializeComponent() {
this.setTitle("TicTacToe");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(400, 400);
this.setLocationRelativeTo(null);
this.setResizable(false);
this.setContentPane(pan);
GridLayout gl = new GridLayout(3,3);
pan.setLayout(gl);
for (JButton jButton : tab_but) {
jButton = new JButton();
pan.add(jButton);
jButton.addActionListener(new ButtonListener());
}
this.setVisible(true);
}
class ButtonListener implements ActionListener{
public void actionPerformed(ActionEvent e) {
if (player1) {
((JButton)e.getSource()).setText("X");
checkWin();
player1=false;
}
else {
((JButton)e.getSource()).setText("O");
player1=true;
}
}
}
public void checkWin() {
if(tab_but[0].getText().equals("X")) {
System.out.println("hi");
}
}
}
As you can see I'm trying to check with the method checkWin()
if the text of the first button is an "X". But the console returns java.lang.NullPointerException
even though the X has been written on the first button (when I clicked on the first button)