6

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();

adhg
  • 10,437
  • 12
  • 58
  • 94
Joe C
  • 1,788
  • 2
  • 17
  • 27

3 Answers3

11

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

Jeff Burka
  • 2,571
  • 1
  • 17
  • 30
4

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.

Andbdrew
  • 11,788
  • 4
  • 33
  • 37
  • 1
    I think the same as @Andbdrew. If you are sure you cannot go without simulating the click programmatically then use doClick() otherwise if you are only after the functionality do it by introducing a common function that will be called by computer move and player's click. – Boro Apr 12 '11 at 00:07
3

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"));
Cerbrus
  • 70,800
  • 18
  • 132
  • 147
Ander Juaristi
  • 328
  • 3
  • 12