import java.awt.EventQueue;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class Shrewmouse extends JFrame implements Runnable {
private JLabel[] mouses; //存放顯示底數的標簽數組
private ImageIcon imgMouse; //地鼠圖片對象
public static void main(String args[]){
EventQueue.invokeLater(new Runnable(){
public void run(){
try{
Shrewmouse frame=new Shrewmouse(); //創建窗體
frame.setVisible(true); //顯示窗體
new Thread(frame).start(); //啟動線程
}catch(Exception e){
e.printStackTrace();
}
}
});
}
public Shrewmouse(){
super();
this.setResizable(false); //禁止調整窗體大小
this.getContentPane().setLayout(null); //窗體不使用布局管理器
this.setTitle("簡易的打地鼠遊戲"); //設置窗體標題
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
ImageIcon img=new ImageIcon(getClass().getResource("background.jpg"));
//初始化背景圖片
imgMouse=new ImageIcon(getClass().getResource("mouse1.jpg"));
//初始化地鼠圖片對象
mouses=new JLabel[6]; //創建顯示地鼠的標簽數組
for(int i=0;i<6;i++){ //遍歷數組
mouses[i]=new JLabel(); //初始化每壹個數組元素
mouses[i].setSize(imgMouse.getIconWidth(),imgMouse.getIconHeight());
//設置標簽與地鼠圖片相同大小
mouses[i].addMouseListener(new MouseAdapter(){//為標簽添加鼠標事件監聽適配器
/**
* 處理鼠標單擊事件的方法
*/
@Override
public void mouseClicked(MouseEvent e){
Object source=e.getSource(); //獲取事件源,即地鼠標簽
if(source instanceof JLabel){ //如果事件是標簽組件
JLabel mouse=(JLabel)source; //強制轉換為JLabel標簽
mouse.setIcon(null); //取消標簽圖標
}
}
});
this.getContentPane().add(mouses[i]); //添加顯示地鼠的標簽到窗體
}
mouses[0].setLocation(253, 300); //設置每個標簽的位置
mouses[1].setLocation(333, 250);
mouses[2].setLocation(388, 296);
mouses[3].setLocation(362, 364);
mouses[4].setLocation(189, 353);
mouses[5].setLocation(240, 409);
final JLabel backLabel=new JLabel(); //創建顯示背景的標簽
backLabel.setBounds(0, 0, img.getIconWidth(), img.getIconHeight());
this.setBounds(100,100,img.getIconWidth(),img.getIconHeight());
backLabel.setIcon(img); //添加背景到標簽
this.getContentPane().add(backLabel); //添加背景標簽到窗體
}
/**
* 線程的核心方法
*/
public void run(){
while(true){ //使用無限循環
try{
Thread.sleep(3000); //使線程休眠3秒
int index=(int)(Math.random()*6); //生成隨機的地鼠索引
if(mouses[index].getIcon()==null){ //如果地鼠標簽沒有設置圖片
mouses[index].setIcon(imgMouse); //為該標簽添加地鼠圖片
}
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}