欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-03-05 19:02:25
本文实例讲述了java基于线程实现带有滚动效果的label标签。分享给大家供大家参考。具体如下: import java.awt.graphics; impor...

本文实例讲述了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程序设计有所帮助。