OK, so I'm creating a Tic Tac Toe GUI. I currently having a working frame of 3x3 buttons that will change to either an X or O. My issue is implementing a JLabel on the top of the buttons. The label keeps track of who's turn it is and will change from either "O's turn" or "X's turn" however I can't seem to get the JLabel to update (only spouts errors). Here's a portion of my code showing how Trying to implement this. The program runs fine but as soon as I add the (turn.setText("O's turn");) I get errors.
Any feedback as to why this may not be working would be appreciated.
import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class TicTacToe extends JFrame { XOButton[] xob = new XOButton[9]; private JLabel turn; public static int state; public TicTacToe() { super("TicTacToe"); //add XOButtons to panel JPanel center = new JPanel(); state = 0; JLabel turn = new JLabel("X's turn"); center.setLayout(new GridLayout(3, 3, 2, 2)); //action listener ButtonListener bl = new ButtonListener(); for (int i = 0; i < 9; i++) { xob[i] = new XOButton(); xob[i].addActionListener(bl); center.add(xob[i]); } //add panel to frame setLayout(new BorderLayout()); add(center, BorderLayout.CENTER); add(turn, BorderLayout.NORTH); } //inner action listener class private class ButtonListener implements ActionListener { @Override public void actionPerformed(ActionEvent ae) { for (int i = 0; i < 9; i++) { if(ae.getSource() == xob[i] && xob[i].getState() == XOButton.NONE && state == 0) { xob[i].setState(XOButton.X); state = 1; //turn.setText("O's turn"); } else if(ae.getSource() == xob[i] && xob[i].getState() == XOButton.NONE && state == 1) { xob[i].setState(XOButton.O); state = 0; } } } } }
"... I get errors"-- and you'll want to show us those errors as well as indicate which line causes it. Otherwise we'll have a hard time understanding what your problem may be.turnvariable and the solution is not to do this.