1 Replies - 5046 Views - Last Post: 22 November 2010 - 01:45 AM Rate Topic: -----

#1 jaythewebripper  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 29
  • Joined: 17-June 10

updating label text dynamically in Java Swing.

Posted 21 November 2010 - 11:27 PM

Hi guys..!

I am creating a simple download manager in Java swing...! I have used different threads for different tasks in the download manager.

Thread1-> main
Thread2-> downloadSpeedTracker
Thread3-> SwingUIRendrer

In this application I am calculating the download speed by creating a thread in class downloadSpeedTracker and I am recalculating this speed after every second. I have created Thread3 in SwingUIRendrer class. Now I want to send this calculated speed to my SwingUIRendrer class.

I want to continuously update this calculated speed on the SwingUI.
How do I achieve this...?

Is This A Good Question/Topic? 0
  • +

Replies To: updating label text dynamically in Java Swing.

#2 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 2388
  • View blog
  • Posts: 5,013
  • Joined: 11-December 07

Re: updating label text dynamically in Java Swing.

Posted 22 November 2010 - 01:45 AM

You're using a JLabel, right? Calling setText(newString) should do the trick.

If you're talking about how to send the data between the classes, the Observer design pattern sounds like a good bet. Basically, put a method in SwingUiRenderer:

public void update(DownloadSpeedTracker tracker, String progress) {
   JLabel label = /*code to retrieve the correct label*/

Now DownloadSpeedTracker needs to be able to register and keep track of observers (user interfaces) You need a few methods:

private List<SwingUIRenderer> observers = new ArrayList<SwingUIRenderer>();

public void addObserver(SwingUIRenderer observer) {

private void updateAllObservers(String progress) {
  for(SwingUIRenderer o : observers) {
    o.update(this, progress);

How it works....

Create your interface and your threads. Register the interface as an observer on all of your threads. When you want a thread to update its progress, simply call the updateAllObservers method.

Now, I have missed an important part of the pattern. It's up to you if you do this or not... but you should create an interface DownloadProgressObserver and have the update() method in it. Your UI should implement this interface and your thread should store a List of DownloadProgressObserver instead of your UI class. This will allow you to (for example) write a text file logger that implements the interface and simply register it with all your threads. Any time you update the UI, the logger will be updated too.
Was This Post Helpful? 2
  • +
  • -

Page 1 of 1