java - Java Swing 中的跑马灯效果

标签 java swing marquee

如何在Java Swing中实现跑马灯效果

最佳答案

这是一个使用 javax.swing.Timer 的例子。

Marquee.png

import java.awt.EventQueue;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.Timer;

/** @see http://stackoverflow.com/questions/3617326 */
public class MarqueeTest {

    private void display() {
        JFrame f = new JFrame("MarqueeTest");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        String s = "Tomorrow, and tomorrow, and tomorrow, "
        + "creeps in this petty pace from day to day, "
        + "to the last syllable of recorded time; ... "
        + "It is a tale told by an idiot, full of "
        + "sound and fury signifying nothing.";
        MarqueePanel mp = new MarqueePanel(s, 32);
        f.add(mp);
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
        mp.start();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new MarqueeTest().display();
            }
        });
    }
}

/** Side-scroll n characters of s. */
class MarqueePanel extends JPanel implements ActionListener {

    private static final int RATE = 12;
    private final Timer timer = new Timer(1000 / RATE, this);
    private final JLabel label = new JLabel();
    private final String s;
    private final int n;
    private int index;

    public MarqueePanel(String s, int n) {
        if (s == null || n < 1) {
            throw new IllegalArgumentException("Null string or n < 1");
        }
        StringBuilder sb = new StringBuilder(n);
        for (int i = 0; i < n; i++) {
            sb.append(' ');
        }
        this.s = sb + s + sb;
        this.n = n;
        label.setFont(new Font("Serif", Font.ITALIC, 36));
        label.setText(sb.toString());
        this.add(label);
    }

    public void start() {
        timer.start();
    }

    public void stop() {
        timer.stop();
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        index++;
        if (index > s.length() - n) {
            index = 0;
        }
        label.setText(s.substring(index, index + n));
    }
}

关于java - Java Swing 中的跑马灯效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3617326/

相关文章:

java - 如何检测 Mac OS 的右键单击事件

java - Android,动态更改 View ,添加/删除新组件

java - 为什么java swing的setVisible要这么久?

java - 将这个 "Marquee code"添加到我的 Jframe 中的 JLabel

jquery - 向上滑动 <p>

java - Maven 提供的依赖项的 ClassNotFoundException

java - "static this"关键字会带来哪些问题或好处?

java - 学生/研究生项目中的经理类(class)问题

java - 如何将变量从 jtextfield 传递到另一个 JFrame/类中的另一个 jtextfield?

javascript - 无缝 jQuery 选框?