import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

class OpenWindows{
public static void main(String[] args){
JFrame.setDefaultLookAndFeelDecorated(true);
JFrame frame=new JFrame(“开窗户游戏”);
frame.getContentPane().add(new Mainpanel());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.pack();
frame.setVisible(true);
}
}
class Mainpanel extends JPanel{
PanelC pc=new PanelC();
PanelS ps=new PanelS(pc);
public Mainpanel(){
this.setLayout(new BorderLayout());
this.add(pc,”Center”);
this.add(ps,”South”);
}
}
//方块面板
class PanelC extends JPanel{
JButton[] winbutton=new JButton[25];
Color c;
public PanelC(){
this.setLayout(new GridLayout(5,5));
for(int i=0;i<25;i++){ winbutton[i]=new JButton(); winbutton[i].setActionCommand(String.valueOf(i)); c=winbutton[i].getBackground(); //获得默认颜色 winbutton[i].addActionListener(new OpenOther()); this.add(winbutton[i]); } this.setPreferredSize(new Dimension(300,300)); } class OpenOther implements ActionListener{ public void actionPerformed(ActionEvent a){ String y=a.getActionCommand(); int x=Integer.parseInt(y); Select(x); IsWin(); } //判断九种情况 private void Select(int x){ if(x==0){ ChangeColor(winbutton[x]); ChangeColor(winbutton[x+1]); ChangeColor(winbutton[x+5]); }else if(x>0 && x<4){ ChangeColor(winbutton[x]); ChangeColor(winbutton[x-1]); ChangeColor(winbutton[x+1]); ChangeColor(winbutton[x+5]); }else if(x==4){ ChangeColor(winbutton[x]); ChangeColor(winbutton[x-1]); ChangeColor(winbutton[x+5]); }else if(x==20){ ChangeColor(winbutton[x]); ChangeColor(winbutton[x-5]); ChangeColor(winbutton[x+1]); }else if(x==24){ ChangeColor(winbutton[x]); ChangeColor(winbutton[x-5]); ChangeColor(winbutton[x-1]); }else if(x>20 && x<24){ ChangeColor(winbutton[x]); ChangeColor(winbutton[x-5]); ChangeColor(winbutton[x-1]); ChangeColor(winbutton[x+1]); }else if(x%5==0){ ChangeColor(winbutton[x]); ChangeColor(winbutton[x-5]); ChangeColor(winbutton[x+1]); ChangeColor(winbutton[x+5]); }else if(x%5==4){ ChangeColor(winbutton[x]); ChangeColor(winbutton[x-5]); ChangeColor(winbutton[x-1]); ChangeColor(winbutton[x+5]); }else{ ChangeColor(winbutton[x]); ChangeColor(winbutton[x-5]); ChangeColor(winbutton[x-1]); ChangeColor(winbutton[x+1]); ChangeColor(winbutton[x+5]); } } //改变周围颜色函数 private void ChangeColor(JButton winbutton){ if(winbutton.getBackground()==c) winbutton.setBackground(Color.white); else winbutton.setBackground(c); } //判断是否胜出 private void IsWin(){ int a=1; for(int i=0;i<25;i++) if(winbutton[i].getBackground()==Color.white) a++; if(a>25)
JOptionPane.showMessageDialog(null,”恭喜过关”);
}
}
}
class PanelS extends JPanel{
JLabel label=new JLabel(“开窗户游戏”);
JButton restart=new JButton(“重置”);
PanelC pc;
public PanelS(PanelC pc){
this.pc=pc;
restart.addActionListener(new Reset());
this.add(label);
this.add(restart);
}
class Reset implements ActionListener{
public void actionPerformed(ActionEvent a){
for(int i=0;i<25;i++){ pc.winbutton[i].setBackground(pc.c); } } } }