[Java]
Package com. han;
Import java. awt. BasicStroke;
Import java. awt. Color;
Import java. awt. Container;
Import java. awt. Graphics2D;
Import java. util. Random;
Import javax. swing. JFrame;
/**
* Use a thread to draw dynamic lines in a Swing window (top-level iner, which differs from a JFrame in space with more title bars ).
*
* @ Author HAN
*
*/
Public class ThreadAndSwing_3 extends JFrame {
/**
*
*/
Private static final long serialVersionUID =-913556444768132509L;
Static Thread thread;
Container container;
Enum Colors {
BLACK (Color. BLACK ),
BLUE (Color. BLUE ),
CYAN (Color. CYAN ),
GREEN (Color. GREEN ),
ORANGE (Color. ORANGE ),
YELLOW (Color. YELLOW ),
RED (Color. RED ),
PINK (Color. PINK ),
LIGHT_GRAY (Color. LIGHT_GRAY );
Private Color c;
Private Colors (Color c ){
This. c = c;
}
Public Color getColor (){
Return this. c;
}
}
Public ThreadAndSwing_3 (){
// TODO Auto-generated constructor stub
Container = getContentPane ();
Container. setLayout (null );
}
Void paintJFrame (){
Thread = new Thread (new Runnable (){
@ Override
Public void run (){
// TODO Auto-generated method stub
/*
* Creates a graphics context for Container (you can also try it
* For JFrame)
*/
Graphics2D g = (Graphics2D) container. getGraphics ();
Colors [] colors = Colors. values ();
Random random = new Random ();
Int y2 = 30;
Float width = 0;
While (true ){
Try {
Thread. sleep (500 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
E. printStackTrace ();
}
/*
* Returns a contains udorandom, uniformly distributed int value
* Between 0 (aggressive) and the specified value (exclusive)
*/
Color c = colors [random. nextInt (colors. length)]. getColor ();
// System. out. println (c );
G. setColor (c );
G. setStroke (new BasicStroke (width ++ ));
/*
* Draws a line, using the current color, between the points
* (X1, y1) and (x2, y2) in this graphics context's
* Coordinate system.
*/
G. drawLine (30, y2, 100, y2 ++ );
If (y2> 70 ){
Width = 0;
Y2 = 30;
}
}
}
});
Thread. start ();
}
/**
* @ Param args
*/Www.2cto.com
Public static void main (String [] args ){
// TODO Auto-generated method stub
ThreadAndSwing_3 frame = new ThreadAndSwing_3 ();
Frame. setTitle ("Draw dynamic lines in a Swing window using threads ");
Frame. setdefaclocloseoperation (JFrame. EXIT_ON_CLOSE );
Frame. setBounds (100,100,300,200 );
Frame. setVisible (true); // display the frame
/*
* Because g will be null if Graphics g = container. getGraphics ();
* Before the display of the related component
*/
Frame. paintJFrame ();
}
}
Author: Gaowen_HAN