Skip to content
Advertisement

Is there a way to skip a mouse click for ActionListener?

I have a Tic Tac Toe GUI that lets a user play against a computer. I use an actionListener to receive the users mouse clicks on where they want to put their “X” on the board. The problem I have is, the way my code is set up, my GUI waits for a mouse click whenever it’s the computers turn before placing their piece. In other words, the user goes first and puts their “X” piece down wherever they want. After the user goes, the user must click on an empty piece on the board to simulate the computers turn, i.e. to simulate the computer putting down an “O” piece. My goal is to try and make the computer’s piece automatically appear on the board without having the user click an empty piece to simulate the computer’s movement. Here is my code for initializing the board which uses ActionListener:

JavaScript

Here’s the code for how the computer determines where to place a piece (randomized, for now):

JavaScript

Advertisement

Answer

Because the computer should make its move right after the user does his, I believe you can bind it to the same event. This way, whenever the user selects his position, he will trigger the computers move.

You can optionally add a short delay, between those two actions.

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