饺子雨效果图(图片来源于网络)
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/17d2c9dc8238afc812625a71d90aa814.png)
源码
package com.jing;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Arrays;
import java.util.Timer;
import java.util.TimerTask;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class DongZhi extends JPanel{
static{
try{
background = ImageIO.read(DongZhi.class.getResource("2.jpg"));
airplane = ImageIO.read(DongZhi.class.getResource("3.jpg"));
}catch(Exception e){
e.printStackTrace();
}
}
private static final long serialVersionUID = 1L;
public static final int WIDTH = 1000;
public static final int HEIGHT = 693;
public static BufferedImage background;
public static BufferedImage airplane;
private JiaoZi[] flyings = {};
int flyEnteredIndex = 0;
private Timer timer;
private int intervel = 1000/300;
public DongZhi(){
flyings = new JiaoZi[1];
flyings[0] = new JiaoZi();
}
public void paint(Graphics g){
g.drawImage(background,0,0,null);
g.drawImage(background,500,0,null);
for(int i=0;i<flyings.length;i++){
JiaoZi f = flyings[i];
g.drawImage(f.image,f.x,f.y,f.width/6,f.height/6,null);
}
}
public static void main(String[] args) {
JFrame frame = new JFrame("饺子雨");
frame.setBackground(Color.BLACK);
DongZhi game = new DongZhi();
frame.add(game);
frame.setSize(WIDTH, HEIGHT);
frame.setAlwaysOnTop(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
game.action();
}
public void action(){
timer = new Timer();
timer.schedule(new TimerTask(){
public void run(){
flyEnteredIndex++;
if(flyEnteredIndex%40==0){
JiaoZi obj = new JiaoZi();
flyings = Arrays.copyOf(flyings,flyings.length+1);
flyings[flyings.length-1] = obj;
}
for(int i=0;i<flyings.length;i++){
flyings[i].step();
}
repaint();
}
},intervel,intervel);
}
}
package com.jing;
import java.awt.image.BufferedImage;
public class JiaoZi{
protected int x;
protected int y;
protected int width;
protected int height;
protected BufferedImage image;
private int speed = 2;
public JiaoZi(){
image = DongZhi.airplane;
width = image.getWidth();
height = image.getHeight()*2;
x = (int) (Math.random()*(DongZhi.WIDTH-this.width/6));
y = -this.height;
}
public void step(){
y+=speed;
}
}