tags:

views:

466

answers:

3

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

+2  A: 

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.

David Moles
+1  A: 

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 ActionEvents 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();
Adamski
thank you soooo much timer class solved my problem :)
soField
+1  A: 

why don't u try this: labelname.paintImmediately(**labelname**.getVisibleRect());

Mew 3.2