Java实现代码雨特效

渡星河
2023-03-01 / 0 评论 / 6 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2023年03月07日,已超过562天没有更新,若内容或图片失效,请留言反馈。

基于多线程,Swing实现代码雨特效

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class CodeRain extends JPanel implements Runnable {
    public static void main(String[] args) {
        JFrame frame = new JFrame();
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null); // 居中显示
        frame.add(new CodeRain());
        frame.setVisible(true);
    }
    private static final int ROW_COUNT = 30; // 行数
    private static final int COLUMN_COUNT = 60; // 列数
    private static final int FONT_SIZE = 20; // 字体大小
    private static final int LINE_HEIGHT = 30; // 行高
    private static final int UPDATE_INTERVAL = 80; // 更新间隔(毫秒)
    private static final String CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; // 可选字符集
    private static final Color BACKGROUND_COLOR = Color.BLACK; // 背景色
    private static final Color TEXT_COLOR = Color.GREEN; // 文字颜色
    private static final Font FONT = new Font("Courier New", Font.PLAIN, FONT_SIZE); // 字体

    private Random random = new Random();
    private char[][] matrix = new char[ROW_COUNT][COLUMN_COUNT]; // 矩阵,保存每个位置的字符
    private int[] velocities = new int[COLUMN_COUNT]; // 速度,保存每列下落的速度

    public CodeRain() {
        for (int i = 0; i < COLUMN_COUNT; i++) {
            velocities[i] = random.nextInt(3) + 1; // 速度为 1~3
        }
        new Thread(this).start(); // 启动线程
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.setColor(BACKGROUND_COLOR);
        g.fillRect(0, 0, getWidth(), getHeight());
        g.setFont(FONT);
        for (int i = 0; i < ROW_COUNT; i++) {
            for (int j = 0; j < COLUMN_COUNT; j++) {
                char c = matrix[i][j];
                int y = i * LINE_HEIGHT + (int) (LINE_HEIGHT * (1 - (velocities[j] - 1) / 2.0));
                g.setColor((c == 0) ? BACKGROUND_COLOR : TEXT_COLOR);
                g.drawChars(new char[]{c}, 0, 1, j * FONT_SIZE, y);
            }
        }
    }

    @Override
    public void run() {
        while (true) {
            updateMatrix();
            repaint();
            try {
                Thread.sleep(UPDATE_INTERVAL);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void updateMatrix() {
        for (int j = 0; j < COLUMN_COUNT; j++) {
            if (random.nextDouble() < 0.1) { // 有 10% 的概率在该列生成新字符
                matrix[0][j] = CHARACTERS.charAt(random.nextInt(CHARACTERS.length()));
            }
            for (int i = ROW_COUNT - 1; i > 0; i--) {
                matrix[i][j] = matrix[i - 1][j]; // 将该列的所有字符下移一格
            }
            matrix[0][j] = 0; // 清空第一行字符
        }
    }
}

1

评论 (0)

取消