# 实现滚动字幕

# 效果

![](http://cdn.qiniu.liyansheng.top/img/GIF 2024-12-25 17-42-41.gif)

# 案例

import javax.swing.*;
import java.awt.*;

public class ScrollingTextDemo extends Panel {
    private JLabel textLabel;
    private String text = "学生学籍信息管理系统正式上线,方便管理各类重要信息。请尽快登录系统,完成必要的操作。祝学习顺利!! ";
    private int currentIndex = 0;

    public ScrollingTextDemo() {
        setSize(400, 100);

        textLabel = new JLabel(text);
        textLabel.setFont(new Font("宋体", Font.BOLD, 16));
        textLabel.setHorizontalAlignment(SwingConstants.LEFT);
        textLabel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(textLabel, BorderLayout.CENTER);
        add(panel);

        // Timer to update text position
        Timer timer = new Timer(150, e -> scrollText());
        timer.start();
    }

    private void scrollText() {
        currentIndex++;
        if (currentIndex >= text.length()) {
            currentIndex = 0; // Reset index to loop the text
        }
        textLabel.setText(text.substring(currentIndex) + text.substring(0, currentIndex));
    }
}