2
Working with progress bar (JProgressBar
) I faced a problem in PropertyChangeListener
. In fact, not necessarily in PropertyChangeListener
, but yes at the time 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 notice, it is necessary that the property to be updated is "Progress", but that is not what happens. At least not initially. The property that is returned is "state", so the condition is not accepted, and the value of the progress bar 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;
}
}
What exactly is the Task class like? What does it do?
– Victor Stafusa
You are using Swing?
– Victor Stafusa
The Tarefe class is an extension of which class? And how it made you did extension?
– Guilherme Nascimento
Use the Debugger and put a Breakpoint on the line
if("progress".equals(evt.getPropertyName())){
and check the name of all properties, some of them will be what you want, probably you will deduce which is by name.– Paulo Roberto Rosa
The Task class extends from Swingworker: public class Task extends Swingworker<Void, Void>{ protected void doInBackground() throws Exception { int progress = 0; setProgress(0); while(progress < 100){ progress++; setProgress(progress); } Return null; }
– Flavio Santos
Using a breakpoint, the property that is returned is "state".
– Flavio Santos
If you put a
Thread.sleep(100);
before thesetProgress
and let it run for 10 seconds, which happens?– Victor Stafusa
Why do you need that line
if("progress".equals(evt.getPropertyName())){
?– Felipe Avelar
Thread.sleep
before callingsetProgress
causes it to delay the specified time, and soon after complete the task at once.Thread.sleep
as the last command within the while makes everything work perfectly!– Flavio Santos
if("progress".equals(evt.getPropertyName())){
serves to find out if it is the Progress property that is being updated and update the properties bar value as well.– Flavio Santos