My midterm assignment for my comp sci class is that I have to create a tictactoe game. I have 9 individual JPanel objects that represent the tiles, all with the int value "turn" that determines which graphic gets put into the panel. My problem is that I need to make it so that when you click the button within a panel, it changes the value of turns for all of the CellPanel objects within the frame, not just that instance of it, so that next time you take a panel, it puts a new graphic up, instead of the same graphic as before.
My Mid1 class with the main method:
import java.awt.*;
import javax.swing.*;
public class Mid1 extends JFrame {
public Mid1() {
setLayout(new GridLayout(3, 3));
CellPanel panel1 = new CellPanel();
add(panel1);
CellPanel panel2 = new CellPanel();
add(panel2);
CellPanel panel3 = new CellPanel();
add(panel3);
CellPanel panel4 = new CellPanel();
add(panel4);
CellPanel panel5 = new CellPanel();
add(panel5);
CellPanel panel6 = new CellPanel();
add(panel6);
CellPanel panel7 = new CellPanel();
add(panel7);
CellPanel panel8 = new CellPanel();
add(panel8);
CellPanel panel9 = new CellPanel();
add(panel9);
}
public static void main(String[] args) {
Mid1 frame = new Mid1();
frame.setTitle("mid1");
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null); // Center the frame
frame.setVisible(true);
}
}
My CellPanel class:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
class CellPanel extends JPanel implements ActionListener{
Image cross = new ImageIcon("image/x.gif").getImage();
Image not = new ImageIcon("image/o.gif").getImage();
JButton button;
int turn = 0;
int draw;
public CellPanel(){
BorderLayout layout = new BorderLayout();
setLayout(layout);
button = new JButton("Take");
button.setPreferredSize(new Dimension(0,20));
button.addActionListener(this);
this.add(button, layout.SOUTH);
}
public void setTurn(int t){
turn = t;
}
public int getTurn(){
return turn;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
if (draw == 1)
g.drawImage(cross, 0, 0, getWidth(), getHeight(), this);
if (draw == 2)
g.drawImage(not, 0, 0, getWidth(), getHeight(), this);
System.out.println(turn);
/*int mode = (int)(Math.random() * 3);
if (mode == 0) {
g.drawImage(cross, 0, 0, getWidth(), getHeight(), this);
}
else if (mode == 1) {
g.drawImage(not, 0, 0, getWidth(), getHeight(), this);
}*/
}
@Override
public void actionPerformed(ActionEvent e) {
switch(turn) {
case 0:
draw = 1;
this.repaint();
turn = 1;
break;
case 1:
draw = 2;
this.repaint();
turn = 0;
break;
default: turn = 0;
break;
}
this.remove(button);
}
}