Skip to content
Advertisement

Where to put another method in Swing UI thread

I’m making a 2-player Tic-Tac-Toe game in Java using Swing. The UI works as expected but I cannot get it to check for a winner.

I have made three classes Main, gui, and winnerDisplay. The gui class does is responsible for creating a 3×3 grid and buttons, etc. The winnerDisplay class is intended as a display prompt congratulating the winner. I’m assuming the first player chooses ‘X’ symbol. Also the 3×3 grid is numbered from 0 to 8 in a row major fashion. (The word grid here is used in a general sense and not in the GridLayout / 2D matrix sense).

I want to check after each turn of each player whether there is a winner (I will optimise it later because there can only be a winner after at least three moves). If there is a winner or a draw I want another window to pop up and display the name of the winner.

Now the problem : No matter where I place isWon() method, it doesn’t stop the game’s main UI thread and does not check it after every move. I know that UI runs on a different thread but how do I achieve my objective?

This is the Main class :

JavaScript

This is the gui class :

JavaScript

This is the winnerDisplay class :

JavaScript

Advertisement

Answer

The code construct looks good, dont see why the method isWon – is not called. Step through your code in debug – to understand more.

The anonymous action listener will have visibility to the static method defined in the class.

The winnerDisplay frame can be called from within isWon() method, and if you use a dialog instead of a JFrame for the alert – you would get the feedback from the user to terminate the program.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement