Search code examples
javatic-tac-toe

Disabling JButton outside initialize


I am at the end of creating my Tic tac toe game but I encountered a problem with disabling JButton.

After isThisTheEnd method recognize that the game should end, I was planing to disable all buttons, but it is impossible to do outside initialize. Is there a way to do this, also why it is possible to setText for a textField but setEnabled not?

Full code

public void isThisTheEnd()
{
    //vertical
    for(int i=0;i<3;i++)
      if(board[0][i]==board[1][i] && board[1][i]==board[2][i])
            textEnd.setText((turn==1?"X":"O") + " wins!");

    //horizontal
    for(int i=0;i<3;i++)
       if(board[i][0]==board[i][1] && board[i][1]==board[i][2])
            textEnd.setText((turn==1?"X":"O") + " wins!");

    //diagonal
    if((board[0][0]==board[1][1] && board[1][1]==board[2][2]) || (board[2][0]==board[1][1] && board[1][1]==board[0][2]))
        textEnd.setText((turn==1?"X":"O") + " wins!");
    else 
        nextTurn();
}


 private void initialize() {

    btn1.setBackground(UIManager.getColor("Button.disabledForeground"));
    btn1.setBounds(36, 86, 120, 120);
    window.getContentPane().add(btn1);
    window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    btn1.setBorder(new LineBorder(Color.WHITE));
    btn1.addActionListener(new ActionListener() {
        public void actionPerformed(ActionEvent e) {
            btn1.setText((turn==1?"X":"O"));
            board[0][0]=turn;
            isThisTheEnd();
            btn1.setEnabled(false);
        }
    });

}


Solution

  • // EDIT: Problem was, that the variable was defined inside a function and could not be used in another function, see comments below this answer.

    This was the old solution, not related to the problem in this case:

    Try this:

    SwingUtilities.invokeLater(() -> {
      // Disable buttons here
    });