本文實例講述了Java基于線程實現帶有滾動效果的Label標簽。分享給大家供大家參考。具體如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
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程序設計有所幫助。