Using threads in swing GUI in Java
•
Java
I use the following code to replace a jlabel every 0.5 seconds, using the same sentence, but using another point
Runnable r1=new Runnable() { @Override public void run() { while(true){ try { connectionStatus.setText("Connection Established..."); Thread.sleep(500L); connectionStatus.setText("Connection Established."); Thread.sleep(500L); connectionStatus.setText("Connection Established.."); Thread.sleep(500L); } catch (InterruptedException ex) { } } } }; Thread th1=new Thread(r1); th1.start();
Is this the real purpose of using threads? Does this affect the speed of the program? If what I'm doing is so stupid, is there any other way to do it?
Solution
If you want these operations to run in parallel, the answer is yes
If you update labels at regular intervals, you should choose to use timers
In marginal note:
>You should avoid using while (true) when executing multithreading. You should define a stop Boolean to test in the loop, or use thread if you extend the thread class Interrupted() > when updating UI elements from non EDT threads, you should use swingutilities invokelater
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码