在 Java 中制作元旦特效的代码可能有很多种方法,这里是一个示例代码:
``` import java.awt.; import javax.swing.;
public class NewYearEffect extends JFrame { // 窗口大小 private static final int WIDTH = 400; private static final int HEIGHT = 400;
// 星星的数量 private static final int NUM_STARS = 100;
// 星星的半径范围 private static final int MIN_RADIUS = 2; private static final int MAX_RADIUS = 8;
// 星星的颜色 private static final Color STAR_COLOR = Color.WHITE;
// 星星的运动速度范围 private static final int MIN_SPEED = 1; private static final int MAX_SPEED = 4;
// 星星的位置和速度 private int[] x; private int[] y; private int[] speed;
public NewYearEffect() { // 初始化窗口 setTitle("元旦特效"); setSize(WIDTH, HEIGHT); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); // 窗口居中 setVisible(true);
// 初始化星星的位置和速度
x = new int[NUM_STARS];
y = new int[NUM_STARS];
speed = new int[NUM_STARS];
for (int i = 0; i < NUM_STARS; i++) {
x[i] = (int) (Math.random() * WIDTH);
y[i] = (int) (Math.random() * HEIGHT);
speed[i] = MIN_SPEED + (int) (Math.random() * (MAX_SPEED - MIN_SPEED + 1));
}
}
@Override public void paint(Graphics g) { super.paint(g); // 绘制背景 g.setColor(Color.BLACK); g.fillRect(0, 0, WIDTH, HEIGHT); // 绘制星星 g.setColor(STAR_COLOR); for (int i = 0; i < NUM_STARS; i++) { g.fillOval(x[i], y[i], MIN_RADIUS + (int) (Math.random() * (MAX_RADIUS - MIN_RADIUS + 1)), MIN_RADIUS + (int) (Math.random() * (MAX_RADIUS - MIN_RADIUS + 1)));