package Test;
import java.awt.BorderLayout;
import java.awt.Cursor;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class MainFrame extends JFrame {
private BackgroundPanel backgroundPanel=null;
public static void main(String args[]){
SwingUtilities.invokeLater(new Runnable(){
public void run(){
MainFrame frame=new MainFrame();
frame.setVisible(true);
}
});
}
public MainFrame(){
super();
setTitle("雪花飘落动画");
setSize(628,411);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Image image=new ImageIcon(getClass().getResource("/image/cursor.png")).getImage();
Cursor cursor=getToolkit().createCustomCursor(image, new Point(), "魔棒");
setCursor(cursor);
setResizable(false);
backgroundPanel=new BackgroundPanel();
backgroundPanel.setImage(new ImageIcon(getClass().getResource("/image/bg.jpg")).getImage());
backgroundPanel.addMouseMotionListener(new MouseAdapter(){
public void mouseMoved(MouseEvent e){
SnowFlakeLabel snow=new SnowFlakeLabel();
Point point=e.getPoint();
snow.setLocation(point);
backgroundPanel.add(snow);
}
});
getContentPane().setLayout(new BorderLayout());
getContentPane().add(backgroundPanel,BorderLayout.CENTER);
}
}
package Test;
import java.awt.Container;
import java.awt.Dimension;
import java.awt.Point;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
public class SnowFlakeLabel extends JLabel implements Runnable {
private final static ImageIcon snow=new ImageIcon(SnowFlakeLabel.class.getResource("/image/snowflake.png"));
private int width=snow.getIconWidth();
private int height=snow.getIconHeight();
public SnowFlakeLabel(){
setSize(new Dimension(width,height));
setIcon(snow);
new Thread(this).start();
}
@Override
public void run() {
// TODO Auto-generated method stub
Container parent=getParent();
Point myPoint=getLocation();
while(true){
if(parent==null){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
myPoint=getLocation();
parent=getParent();
}else{
break;
}
}
int sx=myPoint.x;
int sy=myPoint.y;
int stime=(int)(Math.random()*30+10);
int parentHeight=parent.getHeight();
while(parent.isVisible()&&sy<parent.getHeight()-height){
setLocation(sx,sy);
try {
Thread.sleep(stime);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
sy+=2;
}
}
}