How can I click JButton without a user?

I have a JButton, and when a player clicks on it, it tells my event listener that the button is pressed. I want to know that there is a team or something that acts if the player clicked a button.

Like Tic Tac Toe, I have 2 players that can play against each other, but I want to add an option for the computer player and the player. But since the computer cannot actually press the button, I am lost.

Edit: it would be as simple as gridButton2.click() (Button name) .click ();

+6
source share
3 answers

To a large extent. All you have to do is use the doClick() function. See the API for more details.

+11
source

for the tic-tac-toe element, you do not need the computer to click a button. you just need to wait for the person to make a move, and then the computer will select his move and execute the code that will happen if the button is pressed.

+4
source

Just call the actionPerformed() method directly from the ActionListener implementation ActionListener . You can do it as follows:

 actionPerformed(new ActionEvent(gridButton2, ActionEvent.ACTION_FIRST, "youractioncommand")); 
+3
source

Source: https://habr.com/ru/post/885686/


All Articles