[Java]
Package com. han;
Import java. awt .*;
Import javax. swing .*;
/**
* The application of thread interruption in the swing progress bar is used, and the setValue () method of JProgressBar is called in run.
* <P>
* Thread interruption is applied in this example. There are two ways to interrupt the thread:
* <Ul>
* <Li> use the interrupt () method </li>
* <Li> use an infinite loop in run (), and then use a Boolean mark to control the stop of the loop </li>
* </Ul>
* In addition, internal classes and anonymous internal classes are used separately.
*
* @ Author HAN
*
*/
@ SuppressWarnings ("serial ")
Public class ThreadAndSwing extends JFrame {
Static Thread thread;
JProgressBar progressBar;
Public ThreadAndSwing (){
ProgressBar = new JProgressBar ();
ProgressBar. setStringPainted (true );
Container container = getContentPane ();
Container. add (progressBar, BorderLayout. NORTH); // if no layout manager is specified, BorderLayout is used by default. If you do not use the layout manager, you must specify setLayout (new BorderLayout ())
This. setTitle ("use of thread interruption in Swing progress bar ");
This. pack ();
This. setVisible (true );
This. setdefaclocloseoperation (WindowConstants. EXIT_ON_CLOSE );
This. creatThread ();
Thread. start ();
// Thread_instance.setContinue (false); // another thread interruption Method
Thread. interrupt ();
}
Class Thread_instance implements Runnable {
Boolean isContinue = true;
Public void setContinue (boolean B ){
This. isContinue = B;
}
@ Override
Public void run (){
// TODO Auto-generated method stub
Int count = 0;
While (true ){
ProgressBar. setValue (++ count );
Try {
Thread. sleep (1000 );
} Catch (InterruptedException e ){
// TODO Auto-generated catch block
System. out. println ("the current program is interrupted ");
Break;
}
If (! IsContinue ){
Break;
}
}
System. out. println ("here ");
}
}
Void creatThread (){
Thread = new Thread (new Thread_instance ());
}
Static void init (JFrame frame, int width, int height ){
Frame. setSize (width, height );
}
Public static void main (String [] args ){
Init (new ThreadAndSwing (), 300,100 );
}
}
Author: Gaowen_HAN