Progress bar is not updated correctly

2

Working with progress bar ( JProgressBar ) I came across a problem with PropertyChangeListener . In fact, not necessarily in PropertyChangeListener , but rather at the moment of returning the property being updated.

Tarefa tarefa = new Tarefa();
tarefa.addPropertyChangeListener(new PropertyChangeListener() {
     @Override
     public void propertyChange(PropertyChangeEvent evt) {
          if("progress".equals(evt.getPropertyName())){
               int progresso = (Integer) evt.getNewValue();
               barra.setValue(progresso);
          }
     }
});
tarefa.execute();

As you can see, it is necessary that the property to be updated is "progress", but this is not what happens. At least not initially. The property that is returned is "state", so the condition is not accepted, and the progress bar value is not updated.

What could be wrong?

Here is the class Tarefa :

public class Tarefa extends SwingWorker<Void, Void> {
    @Override
    protected Void doInBackground() throws Exception {
        int progresso = 0;
        setProgress(0);
        while(progresso < 100){
             progresso++;
             setProgress(progresso);
        }
        return null;
    }
}
    
asked by anonymous 30.01.2014 / 22:36

2 answers

2

When you run the task, it runs with SwingUtilities.invokeLater(tarefa); .

Remembering that: every Swing structure is not thread-safe .

    
31.01.2014 / 12:53
1

It happens that the code is calling setProgress very fast and when the event is triggered the progress is already at 100%

If you put Thread.sleep( 20 ); inside while you will see that the event will be triggered more often.

NOTE: If the code runs too fast it does not make sense to have a JProgressBar to monitor the progress of the task.

    
31.01.2014 / 11:37