java 动画/滚动文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10028331/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 23:20:00  来源:igfitidea点击:

Animate/scroll text

javaswinguser-interfacetextmarquee

提问by Dina Frinsi megasari

I am wondering to know about how to make scrolling text. Just like text which can scroll from right to the left. How to animate text in Java GUI?

我想知道如何制作滚动文本。就像可以从右向左滚动的文本一样。如何在 Java GUI 中为文本设置动画?

回答by mKorbel

maybe not an answer for OP, but I can't see reason, very simple by implements Swing Timer, (may be with Translucent container) and put there a JLabel, (updates to the JLabelcould be from Arrayof Charsto avoids resize of container), for example

可能不是 OP 的答案,但我看不出原因,很简单的实现Swing Timer,(可能使用半透明容器)并放在那里JLabel,(更新JLabel可能来自ArrayofChars以避免调整容器大小),例如

import java.awt.Color;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JWindow;
import javax.swing.Timer;

public class SlideTextSwing {

    private JWindow window = new JWindow();
    private JLabel label = new JLabel("Slide Text Swing, Slide Text Swing, ..........");
    private JPanel windowContents = new JPanel();

    public SlideTextSwing() {
        windowContents.add(label);
        window.add(windowContents);
        window.pack();
        window.setLocationRelativeTo(null);
        final int desiredWidth = window.getWidth();
        window.getContentPane().setLayout(null);
        window.setSize(0, window.getHeight());
        window.setVisible(true);
        Timer timer = new Timer(20, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                int newWidth = Math.min(window.getWidth() + 1, desiredWidth);
                window.setSize(newWidth, window.getHeight());
                windowContents.setLocation(newWidth - desiredWidth, 0);
                if (newWidth >= desiredWidth) {
                    ((Timer) e.getSource()).stop();
                    label.setForeground(Color.red);
                    mainKill();
                }
            }
        });
        timer.start();
    }

    public void mainKill() {
        Timer timer = new Timer(500, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        timer.start();
    }

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

            public void run() {
                SlideTextSwing windowTest = new SlideTextSwing();
            }
        });
    }
}