Java基于线程实现带有滚动效果的Label标签实例_技术学院_宜昌市隼壹珍商贸有限公司

您好,欢迎访问宜昌市隼壹珍商贸有限公司

400 890 5375
当前位置: 主页 > 新闻动态 > 技术学院

Java基于线程实现带有滚动效果的Label标签实例

发布时间:2026-01-18  |  点击率:

本文实例讲述了Java基于线程实现带有滚动效果的Label标签。分享给大家供大家参考。具体如下:

import java.awt.Graphics;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
 * Java中用线程实现带有滚动效果的Label标签
 */
public class Test extends JFrame {
 private static final long serialVersionUID = -2397593626990759111L;
 private JPanel pane = null;
 private MoveLabel label = null;
 public Test() {
 super("Test");
 pane = new JPanel();
 label = new MoveLabel("带有滚动效果的标签");
 pane.add(label);
 this.getContentPane().add(pane);
 this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 this.setSize(300, 200);
 this.setVisible(true);
 }
 public static void main(String args[]) {
 new Test();
 }
 /**
 * 带有滚动效果的Label标签,可继续拓展很多特效,例如颜色变换、速度变换等
 */
 private class MoveLabel extends JLabel implements Runnable {
 private static final long serialVersionUID = 1891684760189602720L;
 private String text = null;
 private Thread thread = null;
 private int x = 0;
 private int w = 0, h = 0;
 public MoveLabel(String text) {
  super(text);
  this.text = text;
  thread = new Thread(this);
  thread.start();
 }
 public String getText() {
  return text;
 }
 public void setText(String text) {
  super.setText(text);
  this.text = text;
 }
 protected void paintComponent(Graphics g) {
  super.paintComponent(g);
  g.setColor(this.getBackground());
  g.fillRect(0, 0, w = this.getWidth(), h = this.getHeight());
  g.setColor(this.getForeground());
  g.setFont(this.getFont());
  g.drawString(text, x, h - 2);
 }
 public void run() {
  while (true) {
  x -= 2;
  if (x < -w) {
   x = w;
  }
  this.repaint();
  try {
   Thread.sleep(50);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  }
 }
 }
}

希望本文所述对大家的java程序设计有所帮助。

全国统一服务电话

400 890 5375

电子邮箱:879577@qq.com

公司地址:宜昌市西陵区黄河路5号三峡明珠10栋1051室

咨询微信

TEL:13680874598