Search code examples
javanetbeans-8

Java action listener


I am making a tic tac toe game on Java using Netbeans. I hava a 3x3 board layout with buttons. When you click on a button, the button is disabled and the letter "X" or "O" appears as the label for the button. When I test my game out to get 3 "X's" in a row. It doesn't say I win until I click on another button. So it doesn't respond that I won until I click another button. Should I use a mouse released event instead?


Solution

  • gameOver should be called last, as until you've updated the button you won't know if a win condition has been reached

    You can also greatly reduce the code by using the source of the action

    public class Listener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent ae) {
            Object source = ae.getSource();
            JButton btn = (JButton)source;
            btn.setEnabled(false);
            btn.setFont(new Font("Courier New", Font.BOLD, 56));
            counter++;
            if(counter % 2 == 0 && counter < 10){
                btn.setText("O");
                gameText.setText("X's Turn!");                    
            } else {                       
                btn.setText("X");
                gameText.setText("O's Turn!");
            }           
            gameOver();
        }
    }
    

    Your gameOver check is somewhat limited, you could have a look at this example which is used for determining if a win condition in connect 4, but the idea is same.

    If you prefer, this example applies the idea to tic tac toe