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();
}
}
Create a Square class that extends either a JButton or a JPanel that contains a JButton. You can put code in there to handle a button press and draw the button. Use 9 of these in a grid to put on your Board class.
An actual button press should not affect the Square/button directly. It should call a method on the board class that will check that the move is legal and do any other bookkeeping. (Admittedly there isn’t really much to do here, but your game might get more complicated someday.) The Board method should also call a Square method that lets the button know it is pushed and causes it to get redrawn.
In summary, handle everything to do with a square/button in a Square class and everything to do with the whole game in the Board class. Your ultimate goal should be to keep everything as simple as possible and as easy to change as possible.
0