java代码画樱花飘落_樱花的季节,教大家用canvas画出飞舞的樱花树
时间: 2024-03-02 10:50:47 浏览: 356
HTML5 Canvas樱花树木特效
好的,下面是 Java 代码画出飞舞的樱花树:
```java
import javax.swing.*;
import java.awt.*;
import java.util.Random;
public class SakuraTree extends JFrame {
private final int WIDTH = 800;
private final int HEIGHT = 600;
private final int DELAY = 30;
private final int FLOWER_NUM = 50;
private Image buffer;
private Graphics bufferGraphics;
private Random random = new Random();
private Flower[] flowers = new Flower[FLOWER_NUM];
private int[] xPoints = {0, 20, 20, 40, 20, 20, 0};
private int[] yPoints = {0, 20, 40, 20, 20, 0, 20};
public SakuraTree() {
setTitle("Sakura Tree");
setSize(WIDTH, HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setResizable(false);
buffer = createImage(WIDTH, HEIGHT);
bufferGraphics = buffer.getGraphics();
for (int i = 0; i < FLOWER_NUM; i++) {
int x = random.nextInt(WIDTH);
int y = random.nextInt(HEIGHT / 2);
int dx = random.nextInt(5) + 1;
int dy = random.nextInt(5) + 1;
int size = random.nextInt(20) + 10;
flowers[i] = new Flower(x, y, dx, dy, size);
}
Timer timer = new Timer(DELAY, e -> {
bufferGraphics.setColor(Color.WHITE);
bufferGraphics.fillRect(0, 0, WIDTH, HEIGHT);
for (Flower flower : flowers) {
flower.draw(bufferGraphics);
flower.update();
}
repaint();
});
timer.start();
}
@Override
public void paint(Graphics g) {
g.drawImage(buffer, 0, 0, this);
}
private class Flower {
private int x;
private int y;
private int dx;
private int dy;
private int size;
public Flower(int x, int y, int dx, int dy, int size) {
this.x = x;
this.y = y;
this.dx = dx;
this.dy = dy;
this.size = size;
}
public void draw(Graphics g) {
g.setColor(Color.PINK);
for (int i = 0; i < 7; i++) {
int xPoint = x + xPoints[i] * size / 40;
int yPoint = y + yPoints[i] * size / 40;
g.fillOval(xPoint, yPoint, size / 4, size / 4);
}
}
public void update() {
x += dx;
y += dy;
if (x < 0 || x > WIDTH - size / 4) {
dx = -dx;
}
if (y < 0 || y > HEIGHT / 2 - size / 4) {
dy = -dy;
}
}
}
public static void main(String[] args) {
new SakuraTree().setVisible(true);
}
}
```
这个程序使用了 Java Swing 绘制界面,通过 Timer 类定时更新画面。其中,Flower 类代表樱花,包含了绘制和更新的方法。在主程序中创建了 50 朵樱花,并且使用随机数来设置它们的位置、速度和大小。每个樱花使用 7 个点来绘制,颜色为粉色,形状为圆形。它们会在界面中飘动,并且会在到达屏幕边缘时反弹。
阅读全文