与春光共舞,独属于开发者们的春日场景是什么样的?
用java代码生成樱花效果
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class SpringSakura extends JPanel implements ActionListener {
private static final int WIDTH = 800;
private static final int HEIGHT = 600;
private static final int NUM_PETALS = 100;
private static final int MAX_SIZE = 30;
private static final int MIN_SIZE = 10;
private static final int MAX_SPEED = 5;
private static final int MIN_SPEED = 1;
private ListPetal> petals;
private Timer timer;
private Random random;
public SpringSakura() {
setPreferredSize(new Dimension(WIDTH, HEIGHT));
setBackground(Color.decode('#ADD8E6')); // Light blue sky
petals = new ArrayList>();
random = new Random();
for (int i = 0; i NUM_PETALS; i++) {
petals.add(new Petal());
}
timer = new Timer(50, this);
timer.start();
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
drawSky(g);
drawGrass(g);
drawPetals(g);
}
private void drawSky(Graphics g) {
g.setColor(Color.decode('#ADD8E6')); // Light blue sky
g.fillRect(0, 0, WIDTH, HEIGHT);
}
private void drawGrass(Graphics g) {
g.setColor(Color.decode('#008000')); // Green grass
g.fillRect(0, HEIGHT - 100, WIDTH, 100);
}
private void drawPetals(Graphics g) {
for (Petal petal : petals) {
petal.draw(g);
}
}
@Override
public void actionPerformed(ActionEvent e) {
for (Petal petal : petals) {
petal.update();
}
repaint();
}
private class Petal {
private int x;
private int y;
private int size;
private int speed;
private int angle;
public Petal() {
reset();
}
public void reset() {
x = random.nextInt(WIDTH);
y = random.nextInt(HEIGHT / 2);
size = random.nextInt(MAX_SIZE - MIN_SIZE + 1) + MIN_SIZE;
speed = random.nextInt(MAX_SPEED - MIN_SPEED + 1) + MIN_SPEED;
angle = random.nextInt(360);
}
public void draw(Graphics g) {
g.setColor(Color.decode('#FFC0CB')); // Pink petals
g.fillOval(x, y, size, size);
}
public void update() {
y += speed;
if (y > HEIGHT) {
reset();
}
}
}
public static void main(String[] args) {
SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame('春日樱花飘舞');
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new SpringSakura());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
});
}
}
赞4
踩0