无法获得选择效果

时间:2011-04-21 17:02:30

标签: java swing marquee

  

可能重复:
  Marquee effect in Java Swing

我正在尝试获取字幕效果(我们在html中也一样)。但我无法使用此代码执行此操作。如何改进此代码以获得字幕效果?

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

class tester {
JLabel l;

tester() {
JFrame fr=new JFrame();
JPanel p=new JPanel();
l=new JLabel("");
fr.add(p);
p.add(l);
fr.setVisible(true);
fr.setSize(400,400);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}

public void MarqueeEffect() {
  ActionListener ac = new ActionListener() {
    public void actionPerformed(ActionEvent ae) {
      l.setText("To action alone hast thou a right and never at all to its fruits let not the   fruits of action be thy motive; neither let there be in thee any attachment to inaction");
    }
  };
  new Timer(2000,ac).start();
}

public static void main(String args[]) {
  tester t=new tester();
  t.MarqueeEffect();
 }
}

1 个答案:

答案 0 :(得分:1)

您必须延长JLabel并覆盖paintComponent才能带来字幕效果。它不会只是通过设置文本而不扩展JLabel。您可以在自定义的JLabel类中执行类似的操作。

protected void paintComponent(Graphics g)
{         
g.translate((int)((System.currentTimeMillis() / MARQUEE_SPEED_DIV) % (getWidth() * 2)) - getWidth(), 0);         
super.paintComponent(g);        
repaint(REPAINT_WITHIN_MS);     
}