導入Java . lang . math . *;
導入Java . awt . event . *;
導入Java . awt . *;
導入javax . swing . *;
類mainframe擴展jframe實現action listener {//定義整個框架。
私有JButton[]JB = new JButton[8];
private JButton jbs = new JButton(" opening ");
Private JButton jbres = new JButton("重新開始");
private JPanel jp 1 = new JPanel();
private JPanel jp2 = new JPanel();
private int[]n = new int[9];
private int[]n 1 = new int[9];
private int position = 8,p,q;
私有布爾bl,startbl = false
private JLabel JL = new JLabel();
private int count = 0;
private JLabel JL 1 = new JLabel("+integer . tostring(0));
公共主機(){ // frame的構造方法
int I;
for(int j = 0;j & ltn .長度;j++){
n[j]= j;
n 1[j]= n[j];
}
for(I = 0;我& ltjb.lengthI++){ //為每個按鈕分配壹個對應的值,並記錄偵聽器。
JB[I]= new JButton(integer . tostring(I+1));
Jb[i]。setFont(新字體(“號”,字體。粗體,48));
jp2 . add(JB[I]);
jb[i]。addActionListener(this);
}
for(I = 0;我& ltn .長度;i++){
if(n[i] ==位置)
jp2 . add(JL);
其他
jp2 . add(JB[n[I]]);
}
jp2.setLayout(new GridLayout(3,3));//註冊偵聽器
jbs . addactionlistener(this);
jbres . addactionlistener(this);
jp 1 . add(jbs);
jp 1 . add(jbres);
jp 1 . add(JL 1);
jp 1 . set layout(new FlowLayout());//將jp1設置為流布局。
set layout(new BorderLayout());//整體布局是邊界布局。
this.add("North ",jp 1);
this.add("Center ",jp2);
This.setTitle(“拼圖”);
this.setBounds(100,100,300,350);
this . setdefaultcloseoperation(JFrame。EXIT _ ON _ CLOSE);//實現關閉按鈕
this . setresizable(false);
this . set visible(true);
}
public void action performed(action event e){//實現按鈕的事件。
If(e.getSource()==jbres){ //重啟按鈕事件。
for(int j = 0;j & ltn .長度;j++)
n[j]= n 1[j];
reShow();
startbl = true
count = 0;
JL 1 . settext("+integer . tostring(0));
}
Else if(e.getSource()==jbs) //開始按鈕事件
這個。init();
else if(startbl){//Button 1-8移動事件
for(int I = 0;我& ltjb.lengthi++)
if(e.getSource() == jb[i]){
//system . out . println(I+1);
for(int a = 0;a & ltn .長度;a++){
if(n[a]==i)
p = a;
if(n[a]= =位置)
q = a;
}
}
如果(p!= 0 & amp& ampp!= 1。& ampp!= 2)
如果((p-3) == q)
互換(p,q);
如果(p!= 0 & amp& ampp!= 3 & amp& ampp!= 6)
如果((p-1) == q)
互換(p,q);
如果(p!= 2 & amp& ampp!= 5 & amp& ampp!= 8)
if((p+1) == q)
互換(p,q);
如果(p!= 6 & amp& ampp!= 7 & amp& ampp!= 8)
如果((p+3) == q)
互換(p,q);
}
}
Public void swap (int x,int y) {//button 1-8與空白圖片交換。
int z;
z = n[x];
n[x]= n[y];
n[y]= z;
JL 1 . settext("+integer . tostring(++count));
reShow();
win();
}
Public void Init(){ //隨機生成遊戲界面。
int i=0,j,x;
布爾bl;
while(我& lt9){
bl =真;
x =(int)(math . random()* 9);
for(j = 0;j & lt我;j++)
if(n[j] == x)
bl =假;
如果(bl){
n[i++]= x;
n 1[I-1]= x;
}
}
reShow();
startbl = true
count = 0;
JL 1 . settext("+integer . tostring(0));
}
public void show(){//重寫遊戲界面。
for(int I = 0;我& ltn .長度;i++){
if(n[i] ==位置)
jp2 . add(JL);
其他
jp2 . add(JB[n[I]]);
}
jp2 . revidate();
}
Public void win(){ //判斷是否成功。
boolean winbl = true
for(int I = 0;我& ltn .長度;i++)
if(n[i]!=i)
winbl = false
if(winbl){
Joption窗格。顯示消息對話框(這個,“恭喜妳,妳成功了!”+"您使用了"+Integer.toString(count)+ "step "、""、jooptionpane。信息_消息);
startbl = false
}
}
}
公共類拼貼{//主函數類
公共靜態void main(String[] args){
新大型機();
}
}
我之前編的。不是很好。請參考。