import java.awt.*; import java.util.*; import javax.swing.*; public class SleepMethodTest extends JFrame { /** * */ private static final long serialVersionUID = 1L; private Thread t; // 定義顏色數組 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();// 創建隨機對象 private static Color getC() {// 獲取隨機顏色值的方法 return color[rand.nextInt(color.length)]; } public SleepMethodTest() { t = new Thread(new Runnable() {// 創建匿名線程對象 int x = 30;// 定義初始坐標 int y = 50; public void run() {// 覆蓋線程接口方法 while (true) {// 無限循環 try { Thread.sleep(100);// 線程休眠0.1秒 } catch (InterruptedException e) { e.printStackTrace(); } // 獲取組件繪圖上下文對象 Graphics graphics = getGraphics(); graphics.setColor(getC());// 設置繪圖顏色 // 繪制直線并遞增垂直坐標 graphics.drawLine(x, y, 100, y++); if (y >= 80) { y = 50; } } } }); t.start();// 啟動線程 } 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()方法,該方法用于隨機產生Color類型的對象,并且在產生線程的匿名內部類中使用getGraphics()方法獲取Graphics對象,使用該對象調用setColor()方法為圖形設置顏色;調用drawline()方法繪制一條線段,同時線段會根據縱坐標的變化自動調整。
新聞熱點
疑難解答