CJCoding With Joseph
15free / daySign inCreate account

Mastering Java Swing

Highlight Winners - STEP 6

Tic Tac Toe Game

To visually highlight the winning squares, we’ll create a new method called highlightWinningButtons. This method will check for 3 matching X’s or O’s in a row and update their background color. Here’s how it works:

private void highlightWinningButtons() {
    int[][] winConditions = {
        {0, 1, 2}, {3, 4, 5}, {6, 7, 8}, // Rows
        {0, 3, 6}, {1, 4, 7}, {2, 5, 8}, // Columns
        {0, 4, 8}, {2, 4, 6}             // Diagonals
    };

    for (int[] condition : winConditions) {
        String b1 = buttons[condition[0]].getText();
        String b2 = buttons[condition[1]].getText();
        String b3 = buttons[condition[2]].getText();

        if (!b1.isEmpty() && b1.equals(b2) && b2.equals(b3)) {
            for (int index : condition) {
                buttons[index].setBackground(Color.GREEN);
            }
            break;
        }
    }
}
Members only

Keep reading this lesson

You've reached the end of the free preview. Unlock the rest of this lesson plus 27 more lessons in Mastering Java Swing.

  • Unlimited coding questions
  • Unlimited access to all classroom material
  • Weekly live call for questions and guidance
  • 3,000 AI tutor tokens / month
  • Personal SQL database (3 MB)
  • Progress tracking

Cancel any time.