How to model which JButtons was pressed Tic Tac Toe Game

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.

Answers


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]);
}

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.


Need Your Help

Installing phpDocumentor via PEAR, “command not found”

php pear phpdoc

I'm having trobule installing phpDocumentor via PEAR on a CentOS machine and I don't even know if this is pear or php related.

Django access to attributes with self

python django

I have the following Form defined in Django and I do not know why I cannot access to the attribute "username" from within the method "save":

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.