Not to sure about why this code is not working as intended and hoping you could help me figure it out. I am working on a tictactoe game from a series of tutorials that use jbuttons. What i have is a method in my main class that “checksforwin” each time a button is clicked. Using print statements i found that my method does run each time a button is clicked however the getText().equals(“_”) conditions do not operate properly.
This code is part of my tictactoe.java and all works properly. this event is copied 9 times for each button.
public void button1ActionPerformed(ActionEvent e) {
if(button1.getText().equals("")){
if(Main.playerTurn==true){
button1.setText("X");
Main.checkforwin();
Main.playerTurn = false;
}else{
button1.setText("O");
Main.checkforwin();
Main.playerTurn = true;
}
}
}
This code is part of my main.java which houses the checkforwin method. The check for win chunk of code is repeated multiple times for each possible win in tictactoe for both the player 1 and computer(player2).
public class Main {
public static boolean playerTurn = true;
public static boolean playerWon = false;
public static boolean computerWon = false;
public static tictactoe board = new tictactoe();
public static void checkforwin(){
System.out.println("testing1");
//horizontal row 1
if(board.button1.getText().equals("X")){
System.out.println("testing2");
if(board.button2.getText().equals("X")){
if(board.button3.getText().equals("X")){
playerWon = true;
computerWon = false;
System.out.println("Player 1 won");
}
}
}
}
The method will output testing1 every time a button is clicked, however it will never print inside the conditions.
Any help or advice would be greatly appreciated thanks!
My guess is its not picking up the button text change – after the button text change (
button1.setText("X");) etc – you need to add it to the panel again, sopanel.add(button1);or whatever they’re stored on