0

I am trying to build a TicTacToe game and to draw the game every element in my 2d array should be disabled. How to find out if all of my my JButtons in my array is disabled.Here I assigned I created JButton.

for(int row = 0; row < buttons.length; row++){
        for(int column = 0; column<buttons[row].length; column++){
            buttons[row][column] = new JButton();
            this.add(buttons[row][column]);
            buttons[row][column].addActionListener(new tickSquare());

        }
    }

and here I tried to do looping but it does if everything is disabled

    for(int row = 0; row < buttons.length; row++){
            for(int column = 0; column<buttons[row].length; column++){

                if(buttons[row][column].isEnabled() == false){
                    JOptionPane.showMessageDialog(null,labelD);
                }

            }
        }
0

1 Answer 1

1

Don't show the message dialog in the if itself. Use the loop to update a variable and use that variable outside the loop to decide if you have to show the popup or not:

boolean allDisabled = true;

for(int row = 0; row < buttons.length; row++){
    for(int column = 0; column<buttons[row].length; column++){

        if(buttons[row][column].isEnabled()){
            //This button is enabled, so we set allDisabled to false
            allDisabled = false;
        }

    }
}

if(allDisabled) {
    JOptionPane.showMessageDialog(null,labelD);
} else {
    // At least one button is enabled!
}

You can also break the loop to avoid unnecessary loops when an enabled button is found:

boolean allDisabled = true;

loop:
for(int row = 0; row < buttons.length; row++){
    for(int column = 0; column<buttons[row].length; column++){

        if(buttons[row][column].isEnabled()){
            //This button is enabled, so we set allDisabled to false
            allDisabled = false;
            break loop;
        }

    }
}

But I don't like labels and breaks, so if possible I try to avoid using them.

Sign up to request clarification or add additional context in comments.

1 Comment

@AzamatAdylbekov You're welcome! Don't forget to accept the answer if it helped you solve the issue :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.