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
|
import java.awt.*; import java.util.*; import javax.swing.*; public class SleepMethodTest extends JFrame { /** * */ private static final long serialVersionUID = 1L; private Thread t; // 定義顏色數(shù)組 private static Color[] color = { Color.BLACK, Color.BLUE, Color.CYAN, Color.GREEN, Color.ORANGE, Color.YELLOW, Color.RED, Color.PINK, Color.LIGHT_GRAY }; private static final Random rand = new Random(); // 創(chuàng)建隨機(jī)對(duì)象 private static Color getC() { // 獲取隨機(jī)顏色值的方法 return color[rand.nextInt(color.length)]; } public SleepMethodTest() { t = new Thread( new Runnable() { // 創(chuàng)建匿名線程對(duì)象 int x = 30 ; // 定義初始坐標(biāo) int y = 50 ; public void run() { // 覆蓋線程接口方法 while ( true ) { // 無(wú)限循環(huán) try { Thread.sleep( 100 ); // 線程休眠0.1秒 } catch (InterruptedException e) { e.printStackTrace(); } // 獲取組件繪圖上下文對(duì)象 Graphics graphics = getGraphics(); graphics.setColor(getC()); // 設(shè)置繪圖顏色 // 繪制直線并遞增垂直坐標(biāo) graphics.drawLine(x, y, 100 , y++); if (y >= 80 ) { y = 50 ; } } } }); t.start(); // 啟動(dòng)線程 } public static void main(String[] args) { init( new SleepMethodTest(), 100 , 100 ); } // 初始化程序界面的方法 public static void init(JFrame frame, int width, int height) { frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(width, height); frame.setVisible( true ); } } |
JAVA中的休眠是sleep()方法,本例子中定義了getC()方法,該方法用于隨機(jī)產(chǎn)生Color類型的對(duì)象,并且在產(chǎn)生線程的匿名內(nèi)部類中使用getGraphics()方法獲取Graphics對(duì)象,使用該對(duì)象調(diào)用setColor()方法為圖形設(shè)置顏色;調(diào)用drawline()方法繪制一條線段,同時(shí)線段會(huì)根據(jù)縱坐標(biāo)的變化自動(dòng)調(diào)整。