java开发实战1200(II)------------071岁鼠标移动的图片

package Test;

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseMotionAdapter;
import java.net.URL;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class FollowMousePictureFrame extends JFrame {
    private Image img=null;
    private ImageIcon icon=null;
    private JLabel lb_move=new JLabel();
    private JLabel lb_tip=new JLabel();
    
    public static void main(String args[]){
        EventQueue.invokeLater(new Runnable(){
            public void run(){
                FollowMousePictureFrame frame=new FollowMousePictureFrame();
                frame.setVisible(true);
            }
        });
    }
    public FollowMousePictureFrame(){
        super();
        setTitle("随鼠标移动的图片");
        getContentPane().setLayout(null);
        setBounds(100,100,800,600);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        URL url=FollowMousePictureFrame.class.getResource("/image/coney.png");
        img=Toolkit.getDefaultToolkit().getImage(url);
        icon=new ImageIcon(img);
        addMouseMotionListener(new MouseMotionAdapter(){
            public void mouseMoved(final MouseEvent e){
                int x=e.getX();
                int y=e.getY();
                int w=lb_move.getWidth();
                int h=lb_move.getHeight();
                int x1=x-w/2;
                int y1=y-h/2;
                lb_move.setLocation(x1,y1);
                int x2=x1-52;
                int y2=y1+120;
                lb_tip.setLocation(x2,y2);
            
            }
        });
        
        lb_move.setIcon(icon);
        lb_move.setBounds(192,61,124,120);
        getContentPane().add(lb_move);
        addMouseListener(new MouseAdapter(){
            public void mouseClicked(final MouseEvent e){
                if(e.getButton()==MouseEvent.BUTTON3){
                    System.exit(0);
                }
            }
        });
        
        lb_tip.setText("我就跟着你……");
        lb_tip.setBounds(180,191,104,18);
        getContentPane().add(lb_tip);
        Thread thread=new Thread(new FlareThread());
        thread.start();
        
    }
    class FlareThread implements Runnable{
        public void run(){
            while(true){
                int red=(int)(Math.random()*256);
                int green=(int)(Math.random()*256);
                int blue=(int)(Math.random()*256);
                lb_tip.setForeground(new Color(red,green,blue));
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }

}

猜你喜欢

转载自blog.csdn.net/zdm198255/article/details/84302217
今日推荐