Reprint: http://blog.csdn.net/sunyiz/article/details/8004573
About the Java GUI, there is one thing about Swing that is really important
that's the thread!
How to use the GUI thread correctly,
What kind of code should be executed on the GUI thread?
What kind of code should be executed with other threads?
These are all important,
but many of the textbooks on Java do not emphasize these, and even some of them simply ignore this.
So, here I'm going to give the people who started to swing in on this one important concept:
Threads in Swing
---------------------------------------------------------------------------
To illustrate the problem, we'll start by looking at a post:
http://tieba.baidu.com/p/1872190099
This is the post I sent yesterday, which has briefly described the various threads in the GUI
Now, let's review EDT----This critical thread
this What does EDT do? It is responsible for assigning all GUI events
such as when a keyboard button is pressed, the listener assigned to the corresponding control
such as a mouse click, distributed to the listener of the corresponding control
such as: Draw control
So, we generally like to call the EDT GUI thread.
EDT is a queued pattern in which events are queued, followed by
All-in-one drawing, wrapped as a paint event in Swing and then queued to EDT
, and EDT intelligently merges multiple contiguous The Paint event, wrapping them in a paint event
illustrates an important specification: the swing single-threaded specification
"All interface-related updates should be performed in EDT"
is very important, and in the process of writing your Swing program, Please keep in mind that he
---------------------------------------------------------------------------
Now, Let us first set a small goal, and then we go to implement it, to explore and discover the problem
to do a time-varying progress bar, many novice at the beginning, all the implementation of this feature to express tangled
below, let's write a piece of code:
[Java]View PlainCopy
- Public class Progressframe extends JFrame implements ActionListener {
- private JButton btn = new JButton ("Start");
- private JProgressBar bar = New JProgressBar () {
- public void Paint (Graphics g) {
- Super.paint (g);
- System.out.println ("paint");
- }
- };
- Public Progressframe () {
- Init ();
- }
- private void init () {
- Setdefaultcloseoperation (Jframe.exit_on_close);
- SetSize (200);
- Setlocationrelativeto (null);
- SetLayout (new FlowLayout ());
- Add (BTN);
- Add (bar);
- Btn.addactionlistener (this);
- setvisible (true);
- }
- @Override
- public void actionperformed (ActionEvent e) {
- For (int i = 0; I <= ; i++) {
- Bar.setvalue (i * 10);
- }
- }
- public static void Main (string[] args) {
- new Progressframe ();
- }
- }
Our idea is simple, that is, after you click the button, let the progress bar set the value 11 times to achieve the animation effect
But after you run, when you click the button, it's almost instantaneous, the progress bar is full,
"Paint" is printed only once.
---------------------------------------------------------------------------
Is there no delay, too fast?
Let's make a little change to the Actionperformed method:
[Java]View PlainCopy
- @Override
- Public void actionperformed (ActionEvent e) {
- For (int i = 0; I <= ; i++) {
- try {
- Thread.Sleep (200);
- } catch (Interruptedexception E1) {
- E1.printstacktrace ();
- }
- Bar.setvalue (i * 10);
- }
- }
You will find that, after pressing the button, the interface is as stiff as a dead 2 seconds later, the progress bar is still directly full
"Paint" is printed only once.
What is the reason for this?
Let's talk about a rule that you should follow in writing a Swing program:
"Do not execute time-consuming code in the EDT, time-consuming work should have a separate thread to handle"
Because if you let the time-consuming code take up the EDT, the tasks that are drawn and what in EDT will not be available.
These events were pressed to the end of the EDT queue and then the EDT was merged into a Paint event
The result is that Paint only executes once after the last sleep is no longer
Perhaps some people will be very strange, how this actionperformed in EDT to carry out?
Remember what we said about the role of EDT?
It accepts system events that are passed by the toolkit thread.
Then pass the corresponding listener to the corresponding control and execute the corresponding method
So in fact, this actionperformed is executed by the EDT call.
In fact, most of the listener's methods for the Swing control are performed on the EDT
So we want to avoid time-consuming operations in the methods of these listeners, otherwise the interface will die!
---------------------------------------------------------------------------
So how do we change it to achieve this effect?
We need to get this time-consuming job done by threads outside of EDT:
To modify the Actionperformed method again:
[Java]View PlainCopy
- @Override
- public void actionperformed (ActionEvent e) {
- Runnable Runnable = new Runnable () {
- @Override
- public Void Run () {
- For (int i = 0; I <= ; i++) {
- try {
- Thread.Sleep (200);
- } catch (Interruptedexception E1) {
- E1.printstacktrace ();
- }
- Bar.setvalue (i * 10);
- }
- }
- };
- new Thread (runnable). Start ();
- }
We used a separate thread to execute this code,
Now let's do it again, finally, we see the effect we expect, the progress bar slowly increases
"Paint" also printed 11 times, then our program is OK?
The answer is no, because we're doing this and destroying Swing's single-threaded specification.
The interface update operation is not performed in the EDT.
Bar.setvalue (i * 10);
The sentence should be executed in EDT.
So there's a contradiction here? It does not work in EDT, not in EDT ...
---------------------------------------------------------------------------
In fact, we want only bar.setvalue (i * 10); The sentence was executed in EDT.
And Swing offers a powerful tool class: Swingutilities
It provides several powerful methods, here we need: Invokelater This method
The function of this method is to queue a task to the end of EDT, wait for execution,
We will now modify the Actionperformed method again:
[Java]View PlainCopy
- @Override
- Public void actionperformed (ActionEvent e) {
- Runnable Runnable = new Runnable () {
- int i = 0;
- @Override
- public Void Run () {
- For (i = 0; I <= ; i++) {
- try {
- Thread.Sleep (200);
- } catch (Interruptedexception E1) {
- E1.printstacktrace ();
- }
- Swingutilities.invokelater (new Runnable () {
- @Override
- public Void Run () {
- Bar.setvalue (i * 10);
- }
- });
- }
- }
- };
- new Thread (runnable). Start ();
- }
Again, the effect and the same as the last time, also met the specification, happy.
In fact, in order to deal with this kind of problem, Swing provides a powerful class specifically: SwingWorker
About this swingworker I will find time to explain in detail in the future, say so much today first.
---------------------------------------------------------------------------
Of course, there is a small flaw in our program:
[Java]View PlainCopy
- Public static void Main (string[] args) {
- new Progressframe ();
- }
Here, new Progressframe (); The process, in fact, also contains a lot of interface refresh and so on
We should not let this code execute in the main thread, and should put it in the EDT:
Modify this:
[Java]View PlainCopy
- Public static void Main (string[] args) {
- Swingutilities.invokelater (new Runnable () {
- @Override
- public Void Run () {
- new Progressframe ();
- }
- });
- }
---------------------------------------------------------------------------
This is the most important first lesson about Swing: two specs
"All interface-related updates should be performed in EDT"
"Do not execute time-consuming code in the EDT, time-consuming work should have a separate thread to handle"
These two specifications will accompany your Swing program until forever.
Swing: The first lesson on Java interface Programming, how to properly handle threads in the interface