Import java.awt.*;
Import java.util.*;
Import javax.swing.*;
public class Sleepmethodtest extends JFrame {/** * */private static final long serialversionuid = 1L;
Private Thread t; Define color array 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 ()//Create random object private static color Getc () {//Get random color value method return Co
Lor[rand.nextint (Color.length)]; Public sleepmethodtest () {t = new thread (new Runnable () {///create anonymous thread object int x = 30;//define initial coordinate int
y = 50;
public void Run () {//Overwrite thread interface method while (true) {//Infinite loop try {thread.sleep (100);/thread hibernate 0.1 seconds
catch (Interruptedexception e) {e.printstacktrace ();
}//Get component Drawing Context object Graphics Graphics = Getgraphics (); GraphIcs.setcolor (Getc ()),//Set drawing color//Draw straight line and increment vertical coordinate graphics.drawline (x, y, y++);
if (y >=) {y = 50;
}
}
}
});
T.start ()//Boot thread} public static void Main (string[] args) {init (new sleepmethodtest (), 100, 100); }//Initialize the method of the program interface public static void init (JFrame frame, int width, int height) {frame.setdefaultcloseoperation (J
Frame.exit_on_close);
Frame.setsize (width, height);
Frame.setvisible (TRUE); }
}
Hibernation in Java is the sleep () method, which is defined in this example by the Getc () method, which is used to randomly generate a color type object and use the Getgraphics () method to get the graphics object in the anonymous inner class that produces the thread. Use this object to invoke the SetColor () method to set the color for the graphic, call the DrawLine () method to draw a line segment, and the segment will automatically adjust according to the ordinate changes.