Java基于线程实现带有滚动效果的Label标签实例
本文实例讲述了Java基于线程实现带有滚动效果的Label标签。分享给大家供大家参考。具体如下:
importjava.awt.Graphics; importjavax.swing.JFrame; importjavax.swing.JLabel; importjavax.swing.JPanel; /** *Java中用线程实现带有滚动效果的Label标签 */ publicclassTestextendsJFrame{ privatestaticfinallongserialVersionUID=-2397593626990759111L; privateJPanelpane=null; privateMoveLabellabel=null; publicTest(){ super("Test"); pane=newJPanel(); label=newMoveLabel("带有滚动效果的标签"); pane.add(label); this.getContentPane().add(pane); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); this.setSize(300,200); this.setVisible(true); } publicstaticvoidmain(Stringargs[]){ newTest(); } /** *带有滚动效果的Label标签,可继续拓展很多特效,例如颜色变换、速度变换等 */ privateclassMoveLabelextendsJLabelimplementsRunnable{ privatestaticfinallongserialVersionUID=1891684760189602720L; privateStringtext=null; privateThreadthread=null; privateintx=0; privateintw=0,h=0; publicMoveLabel(Stringtext){ super(text); this.text=text; thread=newThread(this); thread.start(); } publicStringgetText(){ returntext; } publicvoidsetText(Stringtext){ super.setText(text); this.text=text; } protectedvoidpaintComponent(Graphicsg){ 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); } publicvoidrun(){ while(true){ x-=2; if(x<-w){ x=w; } this.repaint(); try{ Thread.sleep(50); }catch(InterruptedExceptione){ e.printStackTrace(); } } } } }
希望本文所述对大家的java程序设计有所帮助。