Alan Sorrill
Alan Sorrill

Reputation: 47

Updating a jprogress-bar

I'm running an AudioInputStream in a jframe. I have a progress bar on the jframe. I named the jproggressbar "bar". I am trying to get the progress bar to track how far the AudioInputStream is through a song. I'v tried a loop, but every way i try it, the loop ends up making the jframe freeze. Then I cant go about other tasks like closing the window or pausing the AudioInputStream until the song finishes. Could someone please help me?

Upvotes: 0

Views: 90

Answers (2)

Alan Sorrill
Alan Sorrill

Reputation: 47

I found out that the loop has to be implemented in a different thread from the JFrame. as in,

public class Window extends JFrame{
       public int getMusicPosition(){
                  //get the music positional value and return it
       }

       public Window(){
                  new Thread(new BarUpdater()).start();
       }

       public class BarUpdater implements Runnable{
                  public void run(){
                             while(true){
                                        bar.setValue(getMusicPosition());
                             }
                  }
       }
}

Upvotes: 1

kiheru
kiheru

Reputation: 6618

In a way or another you need to update the progress bar in the EDT, and keep processing the stream outside the EDT. One way to do it is using a SwingWorker. You'd do the processing in doInBackground() and update the progress with publish(). Alternatively you can roll your own threading, and use SwingUtilities.invokeLater() when you need to update the progress bar.

Upvotes: 5

Related Questions