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();
}
}
}
}