How to use a JProgressBar correctly

62 Views Asked by At

I am trying to develop a function on a button that reads an excel file and generates a custom formatted .TXT file.

My problem is that I want the loading of the data row by row to be shown in a JProgressBar, also to show in a JLabel the name of the code that is currently being read from the Excel file, the whole function runs correctly but neither the bar nor the Jlabel is updated in real time, only the Bar is filled when the .txt is generated and the Jlabel only shows the last record.

I have used the function Thread.sleep(5*1000); between rows of the Excel file to pause the function for 5 seconds, thinking that it is not displayed on the screen due to the speed of the process since the files only contain 5 rows and 4 columns, but although there is a pause in that pause, neither the bar is updated nor the Jlabel.

I leave the code that I am using to generate this:

Libraries I am using:

  • commons-collections4-4.3
  • commons-compress-1.18
  • poi-4.1.0
  • poi-ooxml-4.1.0
  • poi-ooxml-schemas-4.1.0
  • xmlbeans-3.1.0

Just in case the content of the Excel file is:

Example

I leave the complete function where I read the columns and generate the process:


    jProgressBar1.setMaximum(5);
        
    List<String> columnas = Arrays.asList("Name", "Size", "Type", "Condition");
               
    Map<String, Integer> mapNombresColumnas = new HashMap<>();
               
    final int filaNombresColumnas = 0;
        
     JFileChooser chooser = new JFileChooser(); 
     FileNameExtensionFilter filter = new FileNameExtensionFilter("Excel files", "xlsx"); 
     chooser.setFileFilter(filter); 
     chooser.setDialogTitle("Open file"); 
     chooser.setAcceptAllFileFilterUsed(false);
               
     if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){ 
        String ruta1 = chooser.getSelectedFile().toString();//.concat(".xlsx"); 
            
        File archivoXLSX = new File(ruta1); 

        try {
                
            XSSFWorkbook libro = new XSSFWorkbook(archivoXLSX);
                
            org.apache.poi.ss.usermodel.Sheet sheet = libro.getSheetAt(0);
                
            Row filaNombresColumna = sheet.getRow(filaNombresColumnas);
                
            Iterator<Row> rowIterator = sheet.iterator();
            Row row;
            row=filaNombresColumna;
                
            row.cellIterator().forEachRemaining(cell -> {
                
                String valorCelda = cell.getStringCellValue().trim();
                if (!valorCelda.isEmpty()) {
                    mapNombresColumnas.put(valorCelda, cell.getColumnIndex());
                }
            });
                
            int indiceDatos = filaNombresColumnas + 1;
            Row filaDatos = null;
                   
            int cont1 = 0, cont2 = 0;
                  
            int conteo = 1;
                  
            FileWriter fichero = new FileWriter("C:/Test/Result.txt");
                
            fichero.write("Results");
            fichero.write("\r\n");
               
            while ((filaDatos = sheet.getRow(indiceDatos++)) != null) {

                cont1++; cont2=0; 
                
                jProgressBar1.setValue(jProgressBar1.getValue() + 1);
                
                Thread.sleep(5*1000);
                
                String Text = "inicio"; 
                
                int cont = 1;
                
                for (String col : columnas) {
                        
                    cont2++;
                      
                    Cell celda = filaDatos.getCell(mapNombresColumnas.get(col));
                  
                    if(celda == null){
                  
                        Text = Text +"|Ninguno";
                  
                    }else{
                      
                        switch(celda.getCellType()){
                  
                            case STRING:
                          
                                String texto = celda.getStringCellValue();
                                //System.out.println(texto);

                                Text = Text + "|" + texto;
                
                           
                            break;
                           
                            case BLANK:
                          
                                Text = Text + "|";
                                
                            break;     
                           
                            case NUMERIC:
                          
                                int numero = (int) celda.getNumericCellValue(); 
                                String numeroString = Integer.toString(numero); 
                                Text = Text + "|" + numeroString;
                          
                            break;
                          
                            case FORMULA:
                        
                                switch(celda.getCachedFormulaResultType()){
                          
                                    case NUMERIC:
                                    
                                        int numero2 = (int) celda.getNumericCellValue(); 
                                        String numeroString2 = Integer.toString(numero2); 
                                        Text = Text + "|" + numeroString2;
                                  
                                    break;
                                  
                                    case STRING:
                                  
                                        texto = celda.getStringCellValue();
                                        Text = Text + "|" + texto;
                                  
                                    break;
                              
                                }
                          
                            break;
                          
                            case _NONE:
                          
                                System.out.println("NONE");
                          
                            break;
                          
                            default:
                          
                                System.out.println("nulo!!!");
                          
                            break;
                        }
                  
                    }
                  

                }
                    
                String Array[] = Text.split("\\|");
                    
                System.out.println(Text);
                 
                if(!Array[1].equals("Ninguno") && !Array[2].equals("Ninguno")){  
                  
                    jLabel1.setText(Array[1]);
                    
                    String conteoString = Integer.toString(conteo);
                    String conteoformateado = String.format("%14s", conteoString).replace(' ','0');
                    
                    fichero.write("Start+"+ conteoformateado +"+ISSDG10");  
                    fichero.write("\r\n");
                    
                    if(Array[4].equals("DMG") ||
                       Array[4].equals("dmg") ||
                       Array[4].equals("inoperativo") ||
                       Array[4].equals("INOPERATIVO") ||
                       Array[4].equals("inop") ||
                       Array[4].equals("INOP")){
                    
                        fichero.write("Fail+999");
                    
                    }else{
                    
                        fichero.write("Got+34");
                    
                    }
                    
                    fichero.write("\r\n");
                    fichero.write("Free+20++1++++");
                    fichero.write("\r\n");
                    fichero.write("LOCAL+9+");
                    fichero.write("\r\n");
                    fichero.write("INF+"+Array[1]+"+"+Array[2]+Array[3]+"+4");
                    fichero.write("\r\n");
                    fichero.write("C+10+"+conteoformateado);
                    fichero.write("\r\n");
                    
                    conteo ++;

                }
                
                if(Array[1].equals("Ninguno") || Array[2].equals("Ninguno")){
                
                    cont1--; 
                
                }
               
            }
                
            System.out.println("\r\n " + cont1 +"\r\n" + cont2); 
                
            fichero.close();
                
            JOptionPane.showMessageDialog(null, "Generate.");
                
        } catch (org.apache.poi.openxml4j.exceptions.InvalidFormatException ex) {
               
            JOptionPane.showMessageDialog(null, "Error");
               
        } catch (IOException ex) {
            
            Logger.getLogger(jProgressBar.class.getName()).log(Level.SEVERE, null, ex);
            
        } catch (InterruptedException ex) {
            Logger.getLogger(jProgressBar.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


I am testing SwingUtilities which seems to be the solution to this, but at the moment I cannot apply it correctly to my code, I have modified the following lines of code:


cont1++; cont2=0; 
                
                final int percent = cont1;
                
                 try {
                SwingUtilities.invokeLater(new Runnable() {
                  public void run() {
                    updateBar(percent);
                  }
                });
                Thread.sleep(5*1000);
              } catch (InterruptedException e) {
              }

The updateBar function:

public void updateBar(int newValue) {
    jProgressBar1.setValue(newValue);
  }
0

There are 0 best solutions below