java - 无法获得跑马灯效果

标签 java swing marquee

Possible Duplicate:
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();
 }
}

最佳答案

您必须扩展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);     
} 

关于java - 无法获得跑马灯效果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5747332/

相关文章:

java - 如何将焦点设置到 JScrollPane 内的 JTable 的第一行

java - 如何从另一个线程使用服务器更新 java swing gui?

javascript - 没有 <marquee> .. </marquee> 的 HTML 字幕

Android:如何通过点击一个按钮从右到左和左右移动跑马灯文字

IE11 中的 CSS 滚动选框问题

具有 getSize().width、getSize().height 的 Java 小程序

java - 在 Java 中检查三个或更多字符串的相等性

java - BoxLayout 拒绝接受 JButton 的首选大小

java - 覆盖 "equals"方法 : how to figure out the type of the parameter?

java - Jolokia 在服务器端如何工作?