对于comp sci类,我的期中作业是我必须创建一个tictactoe游戏。我有9个代表图块的JPanel对象,所有对象都具有int值“ turn”,该值确定将哪个图形放入面板。我的问题是我需要这样做,以便当您单击面板中的按钮时,它会更改框架中所有CellPanel对象的转弯值,而不仅仅是它的实例,以便下次使用面板上,它将放一个新图形,而不是以前的图形。
我的Mid1类的主要方法是:
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);
}
}
我的CellPanel类:
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);
}
}
最佳答案
使用observer pattern让每个CellPanel
知道游戏状态何时更改;建议了几种实施方式here。尽管CellPanel
可能会有用地扩展JPanel
以建立preferred size,但它仍可以实现Observer
观察者。您的游戏模型可以通知Observable
,该模型应通知侦听单元重绘自身。