Reputation: 2696
i am using a java thread to update jlabel text value in my application but after it updated text on jlabel jlabel showing all past updated values and new value periodically in order via refreshing itself
but when i use same update function within the mouseclick event of jlabel it is updating itself as i expected and showing last value only
what can cause this problem am i missing some methods which mouseclick event internally calls ?
nore:application is japplet
Upvotes: 2
Views: 2799
Reputation: 2748
why don't u try this: labelname.paintImmediately(labelname.getVisibleRect());
Upvotes: 1
Reputation: 54705
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();
Upvotes: 2
Reputation: 51123
Not sure exactly what's going on but I would start by making sure your update happens in the event dispatch thread. Have your updater thread call:
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// ...update the text...
}
});
See the Event Dispatch Thread tutorial.
Upvotes: 3