再一次通过实践抓牢知识:原来标签还可以设置图片,从而作为“背景图片”,标签加上鼠标监听器可以轻松地实现被点击标签的消失,呵呵,标签君原来你这么的可爱!!
package homework;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class daDiShu extends JFrame implements Runnable,MouseListener{
ImageIcon backIcon = new ImageIcon(getClass().getResource("background.jpg")); //背景图片
ImageIcon shrewiIcon = new ImageIcon(getClass().getResource("mouse.png")); //地鼠图片
private JLabel[] shrew = new JLabel[7]; //地鼠标签
//shrew = new JLabel[7];
public daDiShu() {
// TODO Auto-generated constructor stub
setSize(backIcon.getIconWidth(), backIcon.getIconHeight()); //设置JFrame的宽度和高度
setLayout(null);
for(int i = 0; i < 6; i ++){
shrew[i] = new JLabel();
shrew[i].setSize(shrewiIcon.getIconWidth(), shrewiIcon.getIconHeight());
shrew[i].addMouseListener(this //为地鼠标签加上监听器
// new MouseAdapter() {//另外形式的监听器
//
// @Override
// public void mouseClicked(MouseEvent e){
//
// Object t = e.getSource();
// if(t instanceof JLabel){
// JLabel t1 = (JLabel) t;
// t1.setIcon(null);
// }
// }
// }
);
getContentPane().add(shrew[i]);
}
shrew[0].setLocation(253, 300);
shrew[1].setLocation(333, 250);
shrew[2].setLocation(388, 296);
shrew[3].setLocation(362, 364);
shrew[4].setLocation(189, 353);
shrew[5].setLocation(240, 409);
JLabel back = new JLabel(); //设置背景标签
back.setSize(backIcon.getIconWidth(), backIcon.getIconHeight());
back.setIcon(backIcon);
getContentPane().add(back);
}
public void run(){
while(true){
try{
Thread.sleep(1000); //线程休眠
int ran = (int)(Math.random()*6); //随机决定那只地鼠出现
if(shrew[ran].getIcon() == null){
shrew[ran].setIcon(shrewiIcon);
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
public static void main(String[] args){
daDiShu a = new daDiShu();
a.setTitle("打地鼠");
a.setVisible(true);
a.setDefaultCloseOperation(EXIT_ON_CLOSE);
new Thread(a).start();
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
Object t = e.getSource();
if(t instanceof JLabel){
JLabel t1 = (JLabel) t;
t1.setIcon(null);
}
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent e) {
// TODO Auto-generated method stub
}
}