ProgressBar JavaFx

0

I need to start a progressBar when I execute a method and it ends when the method finishes processing, this is the method.

  @FXML
private void procesarImagen(ActionEvent event) {

    ArrayList<String> col = null;
    DecimalFormat df = new DecimalFormat("##.###");
            int cont = 0;
            int acum = 0;
        procesamientoImagen pi = new procesamientoImagen();    




          Map<String, Integer> color = pi.procesmaientoImagen(a);

        TreeMap<String, Integer> treeMap = new TreeMap<>(color);

           for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
 //     labelColor.setStyle("-fx-background-color:"+entry.getKey());


          acum = acum+entry.getValue();

           }
           System.out.println("Total Colores: "+acum);
           pb = new ProgressBar(0);
              int prog = 0;
           col = new ArrayList<>();
         ci =  FXCollections.observableArrayList();
          for (Map.Entry<String, Integer> entry : treeMap.entrySet()) {
 //     labelColor.setStyle("-fx-background-color:"+entry.getKey());
      //   System.out.println("Color: "+entry.getKey()+": "+entry.getValue());
         String colorsImg = entry.getKey();
         float total = (float) (entry.getValue()*100)/acum ;     
         col.add(entry.getKey());
         ci.add(new colorInf("0",df.format(total),colorsImg)); 
         pb.setProgress(prog++);
    //          System.out.println("% "+df.format(total)); 

           }

               TblColor.setItems(ci); 


  // PLANTAS SANAS
   rangosPlagas r = new rangosPlagas();
    ArrayList<String> rango =null;

    procesamientoImagen pi2 = new procesamientoImagen();
    Map<String, Integer> color2 = pi2.procesmaientoImagen(r.plantaSana());
    rango = new  ArrayList<>();
    TreeMap<String, Integer> treeMap2 = new TreeMap<>(color2);
    for (Map.Entry<String, Integer> entry : treeMap2.entrySet()) {
      //  System.out.println(entry.getKey());
        rango.add(entry.getKey());
    }
    int resultado = 0;
    for (String co : col) {
     for (String ra : rango) {      

        if(ra.equals(co) ){
   //         System.out.println(ra+"Esta en el rango");
            resultado = 1;
        }
    }                
        if (resultado == 1) {
            tx.setText("Plantas Sanas");
            colorR.setStyle("-fx-background-color: #2a2475");
        }

    }



    // PLANTAS SANAS

    ArrayList<String> rangoTrips =null;

    procesamientoImagen pi3 = new procesamientoImagen();
    Map<String, Integer> color3 = pi3.procesmaientoImagen(r.trips());
    rangoTrips = new  ArrayList<>();
    TreeMap<String, Integer> treeMap3 = new TreeMap<>(color3);

    for (Map.Entry<String, Integer> entry : treeMap3.entrySet()) {
      //  System.out.println(entry.getKey());
        rangoTrips.add(entry.getKey());
    }
    int resultado2 = 0;
    for (String co : col) {
     for (String ra : rangoTrips) {      

        if(ra.equals(co) ){
     //       System.out.println(ra+"Esta en el rango");
            resultado2 = 1;
        }
    }                



    }
      if (resultado2 == 1) {
            txTrips.setText("Posibles Incidencias de Trips en la planta");
            colorRT.setStyle("-fx-background-color: #6b3d44");
        }





   // PLANTAS SANAS

    ArrayList<String> rangoMinador =null;

    procesamientoImagen pi4 = new procesamientoImagen();
    Map<String, Integer> color4 = pi4.procesmaientoImagen(r.minador());
    rangoMinador = new  ArrayList<>();
    TreeMap<String, Integer> treeMap4 = new TreeMap<>(color4);

    for (Map.Entry<String, Integer> entry : treeMap4.entrySet()) {
      //  System.out.println(entry.getKey());
        rangoMinador.add(entry.getKey());
    }
    int resultado3 = 0;
    for (String co : col) {
     for (String ra : rangoMinador ) {      

        if(ra.equals(co) ){
     //       System.out.println(ra+"Esta en el rango");
            resultado3 = 1;
        }
    }                



    }
      if (resultado3 == 1) {
            txMinador.setText("Posibles Incidencias de Minador en la planta");
            colorRM.setStyle("-fx-background-color: #2f527c");
        }


      // PLANTAS SANAS

    ArrayList<String> rangoPasador =null;

    procesamientoImagen pi5 = new procesamientoImagen();
    Map<String, Integer> color5 = pi5.procesmaientoImagen(r.pasador());
    rangoPasador = new  ArrayList<>();
    TreeMap<String, Integer> treeMap5 = new TreeMap<>(color5);

    for (Map.Entry<String, Integer> entry : treeMap5.entrySet()) {
      //  System.out.println(entry.getKey());
        rangoPasador.add(entry.getKey());
    }
    int resultado4 = 0;
    for (String co : col) {
     for (String ra : rangoPasador ) {      

        if(ra.equals(co) ){
    //        System.out.println(ra+"Esta en el rango");
            resultado4 = 1;
        }
    }                



    }
      if (resultado4 == 1) {
            txPasador.setText("Posibles Incidencias de Pasador en la planta");
            colorRP.setStyle("-fx-background-color: #739bbf");
        }


      modificarCelda(colorFull);
             trips.setVisible(true);
            pasador.setVisible(true);
            minador.setVisible(true);

}
    
asked by Jeisson Hernandez 05.12.2017 в 02:20
source

3 answers

0

I leave this class that I designed when I was learning but it was very useful, you can instantiate them as many times as you want and run processes in parallel without any problem.

public class Barra_Progreso {
private double maximo, actual;
private String informacion, titulo;

private ProgressBar barra;
private Label etiqueta;

public Barra_Progreso(double maximo, double actual, String informacion, String titulo) {
    this.maximo = maximo;
    this.actual = actual;
    this.informacion = informacion;
    this.titulo = titulo;
    //this.segundo_plano();
}

public double getMaximo() {
    return maximo;
}

public void setMaximo(double maximo) {
    this.maximo = maximo;
}

public double getActual() {
    return actual;
}

public void setActual(double actual) {
    this.actual = actual;
}

public String getInformacion() {
    return informacion;
}

public void setInformacion(String informacion) {
    this.informacion = informacion;
}




public void interfaz_grafica(){

    final Stage stage = new Stage();
    stage.setTitle(titulo);

    barra = new ProgressBar();
    barra.setLayoutX(14.0);barra.setLayoutY(26.0);
    barra.setPrefWidth(394.0);barra.setPrefHeight(40.0);
    barra.setProgress(actual);

    etiqueta = new Label(informacion);
    etiqueta.setLayoutX(14.0);etiqueta.setLayoutY(84.0);
    etiqueta.setPrefWidth(394.0);


    Pane panel = new Pane();        
    panel.setPrefWidth(422.0);panel.setPrefHeight(118.0);

    panel.getChildren().addAll(barra,etiqueta);

    Scene escena = new Scene(panel);
    escena.setOnMouseDragged(new EventHandler<MouseEvent>() {
                                        @Override
                                     public void handle(MouseEvent event) {
                                      stage.setX(event.getScreenX());
                                      stage.setY(event.getScreenY());
                                     }
                                    });
    stage.setScene(escena);
    stage.show();


}

public void segundo_plano(){        
            this.interfaz_grafica();

    Task tarea = new Task() {                        
        @Override
        public void run() {
            super.run();
        //    System.out.println("CORRIENDO PROGRAMA: "+actual+" - "+maximo);

             while(true){

                    Platform.runLater(new Runnable() {
                        @Override
                        public void run() {                 
          //                  System.out.println("calculo: "+(actual/maximo));
                            barra.setProgress((actual/maximo));
                            etiqueta.setText(informacion);                                
                        }
                    });

                 double valor = (actual/maximo);  
                 System.out.println("ACTUALIZANDO VALORES ->"+actual+" - "+maximo);
                 if(valor>=1.0) break;  
                try {
                    new Thread().sleep(1000);
                } catch (InterruptedException ex) {
                    Logger.getLogger(Barra_Progreso.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }


        @Override
        protected Object call() throws Exception {             
            return null;
        }
    };

    new Thread(tarea).start();

}

}//fin de la clase
    
answered by 05.12.2017 в 04:27
0

Here I leave a full implementation

public class barra_progreso extends SwingWorker<Double, Integer>{



private registro_masivo rm;
    private final JLabel etiqueta;
    // Barra de progreso que vamos a ir incrementando.
    private final JProgressBar progreso;

/**
 * Le pasamos la etiqueta que tiene que poner "Hecho" cuando termine la
 * tarea y el barra de progreso que queremos que se vaya a actualizar.
 *
 * @param unaEtiqueta
 * @param unaBarraProgreso
 */
public barra_progreso(JLabel unaEtiqueta, JProgressBar unaBarraProgreso, registro_masivo rm) {
    etiqueta = unaEtiqueta;
    progreso = unaBarraProgreso;
    this.rm = rm;
}

/**
 * Tarea que tarda mucho y se ejecutara en un hilo separado.
 */
@Override
protected Double doInBackground() throws Exception {
    System.out.println("doInBackground() esta en el hilo "
            + Thread.currentThread().getName());

    this.rm.lista_estudiantes_carrera(new conexion_base_de_datos().getConexion(),"TSU EN TURISMO");
    int conteo=0;
    int filas=0;

    progreso.setMaximum(rm.getEst_x_carrera().size());
    progreso.setStringPainted(true);


   for(int x=0; x<rm.getEst_x_carrera().size(); x++){ //recorriendo listado de estudiantes
       publish(x);
       System.out.println("_____________________________ESTUDIANTE N°: ("+x+")_________________________________");
       progreso.setString("CI: "+rm.getEst_x_carrera().get(x));

       rm.depurador_estudiantes_semestres(rm.getEst_x_carrera().get(x), "civil");//depurando estudiante por estudiante
        for(int i=0;i<rm.getCant_mat().size();i++){//recorriendo la cantidad de materia por semestre
            System.out.println("semestre "+(i+1)+" cantidad materias= "+rm.getCant_mat().get(i));
            conteo=conteo+rm.getCant_mat().get(i);//contando para sacar el total de materias que debe
        }//fin recorrido cantidad de materia por semestre
            conteo=0; //inicializando la variable para el conteo por cada estudiante de materias que en total debe


}//fin recorrido listado por estudiantes


    progreso.setMaximum(100);
    return  100.0;
}

/**
 * Tarea terminada, SwingWorker llama a este metodo en el hilo de despacho
 * de eventos. Aqui actualizamos la etiqueta para que ponga "Hecho".
 */
@Override
protected void done() {
    System.out.println("done() esta en el hilo "
            + Thread.currentThread().getName());
    etiqueta.setText("hecho");
}

/**
 * SwingWorker llama a este metodo en el hilo de despacho de eventos cuando
 * llamamos a publish() y le pasa los mismos parametros que nosotros
 * pongamos en publish().<br>
 * En este ejemplo, nosotros pasamos el valor de la barra de progreso.
 */
@Override
protected void process(List<Integer> chunks) {
    System.out.println("process() esta en el hilo "
            + Thread.currentThread().getName());
    progreso.setValue(chunks.get(0));
}







public static void main(String args[]){

 // La ventana principal, con una etiqueta que pondrá "Hecho" cuando
    // termine el SwingWorker.
    JFrame ventanaPrincipal = new JFrame();
    JLabel etiqueta = new JLabel("Sin hacer");
    ventanaPrincipal.getContentPane().add(etiqueta);
    ventanaPrincipal.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    ventanaPrincipal.pack();
    ventanaPrincipal.setLocationRelativeTo(null);
    ventanaPrincipal.setVisible(true);

    // Una ventana con la barra de progreso
    JProgressBar barraProgreso = new JProgressBar(0, 100);
    JDialog dialogoProgreso = new JDialog(ventanaPrincipal, "progreso");
    dialogoProgreso.getContentPane().add(barraProgreso);
    dialogoProgreso.pack();
    dialogoProgreso.setLocationRelativeTo(null);

    registro_masivo rm = new registro_masivo();


    // Hacemos visible la barra de progreso y lanzamos
    // el SwingWorker.
    dialogoProgreso.setVisible(true);
    barra_progreso worker = new barra_progreso(etiqueta, barraProgreso,rm);
    worker.execute();
    try {
        // Mostramos el resultado y ocultamos la barra de progreso.
        // Esta llamada se queda bloqueada hasta que termine
        // el SwingWorker. Debemos ocultar la barra de progreso
        // inmediatamente después.
        System.out.println("El resultado es " + worker.get());
    } catch (InterruptedException ex) {
        Logger.getLogger(barra_progreso.class.getName()).log(Level.SEVERE, null, ex);
    } catch (ExecutionException ex) {
        Logger.getLogger(barra_progreso.class.getName()).log(Level.SEVERE, null, ex);
    }


}
    
answered by 05.12.2017 в 19:01
0

You can try this, the progress bar only appears while the method has not finished its execution.

package application;

import javafx.application.Application;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.BorderPane;
import javafx.stage.Stage;

public class BackgroundWorkerDemo extends Application {

    Button taskButton;
    BorderPane mainPane;

    @Override
    public void start(Stage primaryStage) {

        taskButton = new Button("Long Running Task");
        taskButton.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent e) {
                System.out.println("Running task");
                runTask();
            }
        });

        mainPane = new BorderPane();
        mainPane.setTop(taskButton);
        mainPane.setPrefSize(100,50);
        primaryStage.setScene(new Scene(mainPane));
        primaryStage.show();

    }

    private void runTask() {

        ProgressBar progress = new ProgressBar();
        mainPane.setBottom(progress);

        Task<Void> longTask = new Task<Void>() {
            @Override
            protected Void call() throws Exception {
                //Invoke method that execute long duration tasks 
                longDurationMethod();
                return null;
            }
        };

        //When long task ends
        longTask.setOnSucceeded(new EventHandler<WorkerStateEvent>() {
            @Override
            public void handle(WorkerStateEvent t) {
                //Remove progress bar from main pane
                mainPane.getChildren().remove(progress);
            }
        });

        progress.progressProperty().bind(longTask.progressProperty());
        new Thread(longTask).start();

    }

    //Method that execute a long duration task
    public String longDurationMethod() {
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static void main(String[] args) {
        launch(args);
    }

}
    
answered by 25.02.2018 в 09:13