You must ensure that any changes to Swing UI components are performed on the Event Dispatch Thread. Here are two suggestions for accomplishing this:
Timer
You may want to check out javax.swing.Timer if the aim is to periodically refresh the JLabel
text. The timer fires ActionEvent
s periodically on the Event Dispatch Thread:
int delay = 1000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent evt) {
label.setText("foo");
}
};
new Timer(delay, taskPerformer).start();
SwingWorker
Alternatively you may want to consider using a SwingWorker to perform your background processing. The background worker thread can communicate information back to the Event Dispatch thread by calling publish
.
new SwingWorker<Void, String>() {
// Called by the background thread.
public Void doInBackground() {
for (int i=0; i<100; ++i) {
// Do work. Periodically publish String data.
publish("Job Number: " + i);
}
}
// Called on the Event Dispatch Thread.
@Override
protected void process(List<String> chunks) {
// Update label text. May only want to set label to last
// value in chunks (as process can potentially be called
// with multiple String values at once).
for (String text : chunks) {
label.setText(text);
}
}
}.execute();