java实现"烟花燃放"案例

1、新建一个包,在包内新建一个类为 FirePanel,编写如下代码:

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Random;

import javax.swing.JPanel;


class FirePanel extends JPanel implements Runnable, MouseListener {

int x;
int y;

@Override
public void paint(Graphics g) {
super.paint(g);
this.setBackground(Color.BLACK);
g.setColor(Color.YELLOW);
g.fillOval(800, 100, 80, 80);
g.setColor(Color.WHITE);
Random rd = new Random();
for (int i = 0; i < 40; i++) {
int x = rd.nextInt(1024);
int y = rd.nextInt(200);
g.drawString("*", x, y);
}
}


@Override
public void run() {
Graphics g = getGraphics();// 取得画笔
int xClick = x;
int yClick = y;
int yMove = 600; // 地平线的纵坐标
int delay = 1; // 延时,每经过一次循环延时加上一秒
while (yMove > yClick) {
setMyColor(g);
g.fillOval(xClick, yMove, 10, 10);
try {
Thread.sleep(delay++);
} catch (InterruptedException e) {
e.printStackTrace();
}
g.setColor(Color.BLACK);
g.fillOval(xClick, yMove, 10, 10);
yMove -= 5;
}


// 烟花爆破效果,在(xClick,yClick)爆破点,由内到外画出多层半径逐渐变大的圆
for (int i = 0; i < 35; i++) {
setMyColor(g);
int r = 2 * i;
g.drawOval(xClick - r, yClick - r, 2 * r, 2 * r);
r = 2 * (i + 1);
g.drawOval(xClick - r, yClick - r, 2 * r, 2 * r);
r = 2 * (i + 2);
g.drawOval(xClick - r, yClick - r, 2 * r, 2 * r);
try {
Thread.sleep(80);
} catch (InterruptedException e) {
e.printStackTrace();
}
g.setColor(Color.BLACK);
r = 2 * i;
g.drawOval(xClick - r, yClick - r, 2 * r, 2 * r);
r = 2 * (i + 1);
g.drawOval(xClick - r, yClick - r, 2 * r, 2 * r);
r = 2 * (i + 2);
g.drawOval(xClick - r, yClick - r, 2 * r, 2 * r);
}
}


Random rd = new Random();

private void setMyColor(Graphics g) {
int red = 55 + rd.nextInt(200);
int green = 55 + rd.nextInt(200);
int blue = 55 + rd.nextInt(200);
g.setColor(new Color(red, green, blue));
}

@Override
public void mouseClicked(MouseEvent e) {
x = e.getX();
y = e.getY();
new Thread(this).start();
// repaint();


}

@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

}

}


2、再新建一个类为Fireworks,编写如下代码:

import javax.swing.JFrame;
/**
 * 烟花案例
 */
public class Fireworks {
public static void main(String[] args) {
JFrame window = new JFrame("烟花");
FirePanel fp = new FirePanel();
fp.addMouseListener(fp);
window.add(fp);
window.setSize(1024,720);
window.setVisible(true);
window.setLocationRelativeTo(null);//窗体居中
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//关闭窗口时,同时程序退出
}
}

3、运行程序,首先出现一个黑夜满天星窗口,用鼠标点击即可体验在夜空中燃放色彩缤纷的烟花!!!


java实现

你可能感兴趣的:(java实现"烟花燃放"案例)