How to manage a lot of Action Listeners for multiple buttons

Posted by Wumbo4Dayz on Programmers See other posts from Programmers or by Wumbo4Dayz
Published on 2013-10-18T18:35:52Z Indexed on 2013/10/18 22:15 UTC
Read the original article Hit count: 152

Filed under:
|

I have this Tic Tac Toe game and I thought of this really cool way to draw out the grid of 9 little boxes. I was thinking of putting buttons in each of those boxes.

How should I give each button (9 buttons in total) an ActionListener that draws either an X or O?

Should they each have their own, or should I do some sort of code that detects turns in this? Could I even do a JButton Array and do some for loops to put 9 buttons. So many possibilities, but which one is the most proper?

Code so far:

import javax.swing.*;

import java.awt.event.*;
import java.awt.*;
public class Board extends JPanel implements ActionListener{
public Board(){
    Timer timer = new Timer(25,this);
    timer.start();
}
@Override
protected void paintComponent(Graphics g){
    for(int y = 0; y < 3; y++){
        for(int x = 0; x < 3; x++){
                g.drawRect(x*64, y*64, 64, 64);
        }
    }
}
public void actionPerformed(ActionEvent e){
    repaint();
}
}

© Programmers or respective owner

Related posts about java

Related posts about swing