Progressibar using Threads and Scenebiulder

Asked

Viewed 254 times

-1

I’m doing a job, and I wanted to know in a simple way how I solve this, I’m doing a simple program in which it’s almost a game, basically you push a button, the progress bar starts to grow, and adds 1 point on a label. only when I put it to work, it performs both at the same time and the point goes before the progress bar concludes, someone could help me?

Method in Controller:

@FXML Label lb$;  
int dinheiro = 0;  

@FXML  
    public void botão() {  
        BarraDeProgresso b = new BarraDeProgresso(100, 90, barra);  
        new Thread(b).start();  
        dinheiro++;  
        lb$.setText(String.valueOf(dinheiro));  

    }

Class Barradeprogresso:

import javafx.application.Platform;  
import javafx.concurrent.Task;  
import javafx.scene.control.ProgressBar;  

public class BarraDeProgresso extends Task<Void>{

private int qt;
private int tempo;
private ProgressBar barra;


public BarraDeProgresso(int qt, int tempo, ProgressBar barra) {
    this.qt = qt;
    this.tempo = tempo;
    this.barra = barra;
    barra.setProgress(0);
}

public void inicia() {
    double incremento = 1.0/qt;
    for(int i=0; i<qt; i++){
        try {
            Thread.sleep(tempo);
            barra.setProgress(barra.getProgress()+incremento);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

//gets e sets implementados

1 answer

0


The correct way to mark progress in Javafx is by using a bind in conjunction with the methods updateProgress/updateMessage. See the example below:

Task<Void> tarefa = new Task<Void>() {

    @Override
    protected Void call() throws Exception {
        for(int i = 0; i < 10; i++) {
            updateMessage("Pontos: " + i);
            updateProgress(i, 9); // (trabalho atual, total)
            Thread.sleep(1000);
        }
        return null;
    }       
};

Label label = new Label("0");
label.textProperty().bind(tarefa.messageProperty());

ProgressBar pg = new ProgressBar();
pg.progressProperty().bind(tarefa.progressProperty());

The method setProgress Progressbar only puts or changes the value of the property but does not serve to increment.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.