In Java, swing is thread-insecure and single-threaded, and the result is that only the swing components that will be drawn on the screen can be accessed from the event-issuing thread. The event-distributing thread is a thread that invokes a callback method such as paint and update, or an event-handling method defined in the event listener interface, for example, the Actionperformed method in ActionListener is invoked in the event-distribution thread.
Swing is event-driven, so it is natural to update the visible GUI in a callback function, for example, if a button is pressed and the list of items needs to be updated, the update of the list is usually implemented in the Actionperformed method of the event listener associated with the button. It is not normal to update swing components from a thread other than the event-distributing thread.
It is sometimes necessary to update swing components from threads other than the event-distributing thread, for example, there is a time-consuming operation in actionperformed that takes a long time to return, and it takes a long time to see the updated list when the button is activated, and the button stays pressed for a period of only Actionperformed returns, generally time-consuming operations should not be performed in an event-handling method because other events are not triggered until the event is returned, and the interface is similar to a jammed condition, so it may be better to perform more time-consuming operations on separate threads. This will immediately update the user interface and release the event thread to distribute other events.
The Swingutilities class provides two methods: Invokelate and Invoteandwait, all of which allow the event to be queued for the running objects on the thread. The Run method is called when the running object is ranked at the top of the queue for the event distribution. The effect is to allow the event-issuing thread to invoke any one of the code blocks in another thread.
Only the thread is distributed from the event to update the component.
Program Example: Error method for updating components
startButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
GetInfoThread t = new GetInfoThread(Test.this);
t.start();
startButton.setEnabled(false);
}
});
class GetInfoThread extends Thread {
Test applet;
public GetInfoThread(Test applet) {
this.applet = applet;
}
public void run() {
while (true) {
try {
Thread.sleep(500);
applet.getProgressBar().setValue(Math.random() * 100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}