java swing效果_Java Swing中的字幕效果

小编典典

这是使用的示例javax.swing.Timer。

import java.awt.EventQueue;

import java.awt.Font;

import java.awt.event.ActionEvent;

import java.awt.event.ActionListener;

import javax.swing.JFrame;

import javax.swing.JLabel;

import javax.swing.JPanel;

import javax.swing.Timer;

/** @see http://stackoverflow.com/questions/3617326 */

public class MarqueeTest {

private void display() {

JFrame f = new JFrame("MarqueeTest");

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

String s = "Tomorrow, and tomorrow, and tomorrow, "

+ "creeps in this petty pace from day to day, "

+ "to the last syllable of recorded time; ... "

+ "It is a tale told by an idiot, full of "

+ "sound and fury signifying nothing.";

MarqueePanel mp = new MarqueePanel(s, 32);

f.add(mp);

f.pack();

f.setLocationRelativeTo(null);

f.setVisible(true);

mp.start();

}

public static void main(String[] args) {

EventQueue.invokeLater(new Runnable() {

@Override

public void run() {

new MarqueeTest().display();

}

});

}

}

/** Side-scroll n characters of s. */

class MarqueePanel extends JPanel implements ActionListener {

private static final int RATE = 12;

private final Timer timer = new Timer(1000 / RATE, this);

private final JLabel label = new JLabel();

private final String s;

private final int n;

private int index;

public MarqueePanel(String s, int n) {

if (s == null || n < 1) {

throw new IllegalArgumentException("Null string or n < 1");

}

StringBuilder sb = new StringBuilder(n);

for (int i = 0; i < n; i++) {

sb.append(' ');

}

this.s = sb + s + sb;

this.n = n;

label.setFont(new Font("Serif", Font.ITALIC, 36));

label.setText(sb.toString());

this.add(label);

}

public void start() {

timer.start();

}

public void stop() {

timer.stop();

}

@Override

public void actionPerformed(ActionEvent e) {

index++;

if (index > s.length() - n) {

index = 0;

}

label.setText(s.substring(index, index + n));

}

}

2020-03-20

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值