日期:2014-05-20  浏览次数:20809 次

jlabel做滚动文字??
我想在jbuilder做的系统的欢迎窗口上的jlabel上做一个滚动文本,即"欢迎光临"这几个字在jlabel滚动显示,
请问谁有相关代码?或指点一下??

------解决方案--------------------
用多线程吧。。

Java code
    class ScrollText extends Thread
    {
        String str = "        欢迎光临!";
        public ScrollText()
        {
            this.start();
        }
        
        public void run()
        {
            str = str.substring(1,str.length())+str.charAt(0);
            this.lable1.setText(str);//这是个内部内,这里的lable1就是你的那个lable
        }
    }

------解决方案--------------------
Java code
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.io.*;

public class Test extends JPanel {
    private static final long serialVersionUID = 4767050156491994899L;
    private JLabel            label;
    private String            scrolledText;

    public Test() {
        scrolledText = "滚动文字 Demo";
        label = new JLabel(new String(scrolledText));
        this.add(label);

        Thread thread = new Thread(new TextChanger(label));
        thread.start();
    }

    // @Override
    // protected void paintComponent(Graphics g) {
    // super.paintComponent(g);
    //
    // Graphics2D g2d = (Graphics2D) g;
    //
    // }

    private static void createAndShowGUI() {
        JFrame frame = new JFrame("Frame");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400, 400);

        frame.getContentPane().add(new Test());

        frame.setVisible(true);
    }

    public static void main(String[] args) throws Exception {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Test.createAndShowGUI();
            }
        });
    }
}

class TextChanger implements Runnable {
    private JLabel label;

    public TextChanger(JLabel label) {
        this.label = label;
    }

    public void run() {
        try {
            while (true) {
                String text = label.getText();
                if (text.length() > 1) {
                    text = text.substring(1, text.length()) + text.charAt(0);
                    label.setText(text);

                    // Get the frame
                    Component frame = SwingUtilities.getRoot(label);
                    if (frame != null && (frame instanceof JFrame)) {
                        ((JFrame)frame).setTitle(text);
                    }

                    label.repaint();
                }

                Thread.sleep(300);
            }
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}