所需的背景素材与流星素材如下:
背景图:
静态流星:
动态流星:
代码实现:
package liuxing_1;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class LiuXing extends JFrame {
double width;
double height;
public LiuXing() {
Toolkit tk = Toolkit.getDefaultToolkit();// 获得Toolkit对象
this.setIconImage(new ImageIcon("图标.png").getImage());// 设置软件图标
Dimension screensize = tk.getScreenSize();// 获得屏幕大小
width = screensize.getWidth();
height = screensize.getHeight();
this.setBounds(0, 0, (int) width, (int) height);// 设置窗体大小和屏幕一致
// this.setUndecorated(true);// 去掉窗体边框
MeteorPanel m = new MeteorPanel();// 设置窗体课件
this.add(m);
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Thread t=new Thread(m);
t.start();
}
class MeteorPanel extends JPanel implements Runnable {
int count = 5;// 定义5个星星
int[] xx = new int[count];
int[] yy = new int[count];
@Override
public void paint(Graphics g) {
// TODO Auto-generated method stub
super.paint(g);
g.drawImage(new ImageIcon("G:\\个性设计\\流星绘制\\background.jpg").getImage(), 0, 0, (int) width, (int) height, this);// 大的背景图片
g.drawImage(new ImageIcon("G:\\个性设计\\流星绘制\\bar.png").getImage(), 400, 40, this);// 加入星星
for (int i = 0; i < count; i++) {
g.drawImage(new ImageIcon("G:\\个性设计\\流星绘制\\m_03.png").getImage(), xx[i], yy[i], this);// 加入流星
}
}
@Override
public void run() {
// TODO Auto-generated method stub
while (true) {
for (int i = 0; i < count; i++)/* 设置流星出现的位置 */ {
xx[i] = (int) (Math.random() * (width - 200)) + 100;
yy[i] = 0;
}
// 改变每颗流星的丛横坐标,控制流行移动
for (int j = 0; j < 210; j++) {// 210刚好到达页面刷新频率的临界值
// 下一组的流星的出现
for (int a = 0; a < count; a++) {
xx[a] -= 5;// 横坐标-5
yy[a] += 1;// 纵坐标+1
}
repaint();// 重新绘制流星
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
// 流星个数随机,下次产生时间随机
// 每次产生个数随机
count = (int) (Math.random() * 10);
xx = new int[count];
yy = new int[count];
int time = (int) (Math.random() * 200) + 60;// 时间随机产生, +60表示每次间隔的时间
try {
Thread.sleep(time);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
LiuXing m = new LiuXing();
}
}