0

I already written 4 classes for the game all in the Java language. There are for launching the game, game Logic, J Buttons and the game Board. I created and added all 9 Buttons into a Grid Layout using a for loop. Each button has an actionListener.

How to model which J Button the user pressed. If I know that piece of information, I am sure I can use an array of characters to model the game logic.

tenorsax
  • 21,123
  • 9
  • 60
  • 107
Nicholas
  • 679
  • 2
  • 11
  • 29
  • Possible duplicate of [How to get X and Y index of element inside GridLayout?](http://stackoverflow.com/q/7702697/230513) – trashgod Sep 08 '12 at 00:41

2 Answers2

2

Not sure if that is the question, you could use setActionCommand methods to assign an action to a button. And then retrieve it from ActionEvent with getActionCommand(). See How to Use Buttons for more details and examples.

You also can use ActionEvent.getSource() to get the object that originated the event, ie the button that was pressed.

tenorsax
  • 21,123
  • 9
  • 60
  • 107
1

Using separate AbstractAction listeners, it would look something like:

JButton[] buttons = new JButton[9];
for (int i=0; i < buttons.length; i++) {
    buttons[i] = new JButton("X or O here");
    buttons[i].addActionListener(new MyAction());
    add(buttons[i]);
}
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 1
    ehhh .. you are on the right track, but stopping mid-ways: using an Action is _the_ thingy to do. But instead of adding it as mere actionListener, go full blast and do a _setAction_ – kleopatra Sep 08 '12 at 06:37