滚动字幕

昨天培训讲了JPanel的paint方法,突然想到以前看到过滚动字幕是靠paint方法做的,于是乎又是各种百度找模版,写了个滚动字幕的Panel。

做的是左右来回滚动的那种。

package com.raikou.MusicPlayer;

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.Timer;

public class PanelTitle extends JPanel {

    private static final long serialVersionUID = 1L;
    private String message = " ";
    private int xCoordinate = 0;
    private int yCoordinate = 10;
    private int count=0;
    private boolean flag = false;
    private int delay = 0;
    
    public PanelTitle(String message) {
        this.message = message;        
        Timer timer = new Timer(100, new TimerListener());
        timer.start();
    }
    
    public void restr(String message)
    {
        this.message = message;
        xCoordinate = 0;
        
    }
    
    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);
        yCoordinate = getHeight()/2 + 4;
        //System.out.println(getWidth());
        Graphics2D g2 = (Graphics2D)g;
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
        //System.out.println( message.getBytes().length);
        int textWidth = getFontMetrics(g2.getFont()).bytesWidth(message.getBytes(), 0, message.getBytes().length);
        //System.out.println(textWidth);
        
        if(!flag)
        {//设置字符串到达最左端或最右端时停留3秒
            delay++;
            if(delay>30)
            {
                flag = true;
                delay = 0;
            }
        }
        else
        {
        if (textWidth > getWidth())
        {
            if(xCoordinate>=-(textWidth-getWidth()+5)&&count%2==0)
            {
                xCoordinate -= 2;
                if(xCoordinate <=-(textWidth-getWidth()+5))
                {
                    count++;
                    flag = false;
                }
            }
            
            else
                if(xCoordinate <= 5 && count%2!=0)
                {
                    xCoordinate += 2;
                    if(xCoordinate >= 5)
                    {
                        count++;
                        flag = false;
                    }
                }
        }
        }
        g.drawString(message, xCoordinate, yCoordinate);
    }

    class TimerListener implements ActionListener
    {
        public void actionPerformed(ActionEvent e)
        {
            repaint();
        }
    }
}

 

posted @ 2013-09-10 21:51  幻の雷光  阅读(266)  评论(0编辑  收藏  举报