Java写一个动态樱花树代码
时间: 2024-10-21 20:12:08 浏览: 24
在Java中创建一个动态的樱花树动画,我们通常会利用Swing或JavaFX这样的图形用户界面库来构建。这里提供一个简单示例,使用Swing库来创建一个基本的樱花树动画。请注意,这只是一个基础版的代码,实际效果可能会包含更多的细节和交互。
```java
import javax.swing.*;
import java.awt.*;
import java.awt.geom.Ellipse2D;
import java.util.Random;
public class SakuraTree extends JPanel {
private static final int MAX_BLOOMS = 200;
private Random random = new Random();
private Ellipse2D.Double[] blooms;
public SakuraTree() {
setSize(600, 400);
setFocusable(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setPreferredSize(new Dimension(600, 400));
blooms = new Ellipse2D.Double[MAX_BLOOMS];
for (int i = 0; i < MAX_BLOOMS; i++) {
bloom(i);
}
}
private void bloom(int index) {
blooms[index] = new Ellipse2D.Double(
random.nextDouble() * getWidth(),
random.nextDouble() * getHeight(),
10,
20
);
repaint();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setPaint(Color.WHITE);
for (Ellipse2D.Double bloom : blooms) {
if (bloom.width > 0 && bloom.height > 0) {
g2d.draw(bloom);
}
}
}
public static void main(String[] args) {
EventQueue.invokeLater(() -> {
JFrame frame = new JFrame("Dynamic Sakura Tree");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SakuraTree());
frame.pack();
frame.setVisible(true);
});
}
}
阅读全文