Joe C
Joe C

Reputation: 1838

How do I Click a JButton without the user Clicking it?

I have a JButton and when a player clicks it it tell my Action Listener that a button is clicked. What i want to know is that is there a command or something that acts as if a player clicked the button.

Like Tic Tac Toe, i have it so 2 players can play against each other, but i want to add the option for a computer player vs a human player. But since the computer cant actually click the button, i am lost.

Edit: would it be as easy as gridButton2.click() (Name of button).click();

Upvotes: 6

Views: 6676

Answers (3)

Jeff Burka
Jeff Burka

Reputation: 2571

Pretty much. All you need to do is use the doClick() function. See the API for more information.

Upvotes: 11

Ander Juaristi
Ander Juaristi

Reputation: 328

Just call directly the actionPerformed() method from the ActionListenerimplementing class. You can do it the following way:

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

Upvotes: 3

Andbdrew
Andbdrew

Reputation: 11895

for the tic-tac-toe thing, you don't need the computer to click a button. you just have to wait until the human makes a move, then have the computer choose its move and execute the code that happens if the button gets clicked.

Upvotes: 4

Related Questions