babkamen
babkamen

Reputation: 13

ProgressBar when program is running

I'm trying to add to my program progress bar ,when it executes.Actualy I want to add something like this:

public class TestProgressBar extends javax.swing.JFrame {
   public  TestProgressBar Bar;
    public TestProgressBar() {
        initComponents();
        Bar=this;
    }
public void start(){
      //progress bar action
            SwingUtilities.invokeLater(new Runnable() {
              public void run() { 
                for(int i=0;i<100;i++){                
                          jProgressBar1.setValue(jProgressBar1.getValue()+10);  
                    try {
                    Thread.currentThread().sleep(100);
                      } catch (InterruptedException ex) {
                          Logger.getLogger(TestProgressBar.class.getName()).log(Level.SEVERE, null, ex);
                      }
            }
              }
              });
        //program running
   while(true);
}
    public static void main(String args[]) {
     TestProgressBar t=new TestProgressBar();
     t.setSize(320, 320);
     t.pack();
     t.setVisible(true);
     t.start();
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton jButton1;
    private javax.swing.JProgressBar jProgressBar1;
    // End of variables declaration                   
}

but it doesn't work
I found code that implements what i want to do
Code but for met it's messy
So the questrion is how to implement progress bar which changes than program is working? The progress bar value changes but form doesn't show these changes

Upvotes: 0

Views: 997

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285403

You're calling Thread.sleep(...) on the Swing event thread which is putting your application to sleep. The while (true) may also be called on the event thread, but I'm not 100% sure on this.

Solution: don't step on the Swing event thread (or Event Dispatch Thread or EDT) but instead use a background thread for this. Please read Concurrency in Swing to see how to use a SwingWorker to help you create a background thread for this.

Upvotes: 1

Related Questions