Foros del Web » Programación para mayores de 30 ;) » Java »

Hacer ProgressBar

Estas en el tema de Hacer ProgressBar en el foro de Java en Foros del Web. Buen día foreros, tengo un dilema nunca he hecho una barra de progreso, y lo que intento hacer es lo siguiente. Copio un archivo, de ...
  #1 (permalink)  
Antiguo 12/02/2015, 06:52
 
Fecha de Ingreso: junio-2013
Mensajes: 68
Antigüedad: 10 años, 9 meses
Puntos: 1
Hacer ProgressBar

Buen día foreros, tengo un dilema nunca he hecho una barra de progreso, y lo que intento hacer es lo siguiente.

Copio un archivo, de una carpeta a otra dentro del mismo equipo, el problema que tengo es que aveces se tarda entre 10 y 15 segundos, y como puede pasar con el usuario que se desespera y cierra todo sin saber que sigue, copiando el archivo, por tal motivo me he puesto la tarea de poner una barra de proseso pero no entiendo muy bien la dinamica de como funciona por lo tanto dejo el codigo de llava que utilizo para copiar el archivo

int c;
while( (c = in.read() ) != -1) {
out.write(c);
}

lo que indico es que mientras lea el archivo escriba en el origen del mismo cual quier otra información me la pueden pedir

Gracias
  #2 (permalink)  
Antiguo 12/02/2015, 07:00
Avatar de Profesor_Falken  
Fecha de Ingreso: agosto-2014
Ubicación: Mountain View
Mensajes: 1.323
Antigüedad: 9 años, 8 meses
Puntos: 182
Respuesta: Hacer ProgressBar

Buenas,

Lo mejor es que utilices un SwingWorker para ir actualizando segun copias el fichero. Te pongo un ejemplo para que puedas ejecutarlo y copiar lo que necesites. Esta sacado de aqui:http://stackoverflow.com/questions/1...ories-and-file
Código Java:
Ver original
  1. public class FileCopierUtility extends JFrame implements ActionListener, PropertyChangeListener
  2. {
  3.     private static final long serialVersionUID = 1L;
  4.  
  5.     private JTextField txtSource;
  6.     private JTextField txtTarget;
  7.     private JProgressBar progressAll;
  8.     private JProgressBar progressCurrent;
  9.     private JTextArea txtDetails;
  10.     private JButton btnCopy;
  11.     private CopyTask task;
  12.  
  13.     public FileCopierUtility()
  14.     {
  15.         buildGUI();
  16.     }
  17.  
  18.     private void buildGUI()
  19.     {
  20.         setTitle("File Copier Utility");
  21.         setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
  22.  
  23.         addWindowListener(new WindowAdapter()
  24.         {
  25.             @Override
  26.             public void windowClosing(WindowEvent e)
  27.             {
  28.                 if(task != null) task.cancel(true);
  29.                 dispose();
  30.                 System.exit(0);
  31.             }
  32.         });
  33.  
  34.         JLabel lblSource = new JLabel("Source Path: ");
  35.         JLabel lblTarget = new JLabel("Target Path: ");
  36.         txtSource = new JTextField(50);
  37.         txtTarget = new JTextField(50);
  38.         JLabel lblProgressAll = new JLabel("Overall: ");
  39.         JLabel lblProgressCurrent = new JLabel("Current File: ");
  40.         progressAll = new JProgressBar(0, 100);
  41.         progressAll.setStringPainted(true);
  42.         progressCurrent = new JProgressBar(0, 100);
  43.         progressCurrent.setStringPainted(true);
  44.         txtDetails = new JTextArea(5, 50);
  45.         txtDetails.setEditable(false);
  46.         DefaultCaret caret = (DefaultCaret) txtDetails.getCaret();
  47.         caret.setUpdatePolicy(DefaultCaret.ALWAYS_UPDATE);
  48.         JScrollPane scrollPane = new JScrollPane(txtDetails, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
  49.         btnCopy = new JButton("Copy");
  50.         btnCopy.setFocusPainted(false);
  51.         btnCopy.setEnabled(false);
  52.         btnCopy.addActionListener(this);
  53.  
  54.         DocumentListener listener = new DocumentListener()
  55.         {
  56.             @Override
  57.             public void removeUpdate(DocumentEvent e)
  58.             {
  59.                 boolean bEnabled = txtSource.getText().length() > 0 && txtTarget.getText().length() > 0;
  60.                 btnCopy.setEnabled(bEnabled);
  61.             }
  62.  
  63.             @Override
  64.             public void insertUpdate(DocumentEvent e)
  65.             {
  66.                 boolean bEnabled = txtSource.getText().length() > 0 && txtTarget.getText().length() > 0;
  67.                 btnCopy.setEnabled(bEnabled);
  68.             }
  69.  
  70.             @Override
  71.             public void changedUpdate(DocumentEvent e){}
  72.         };
  73.  
  74.         txtSource.getDocument().addDocumentListener(listener);
  75.         txtTarget.getDocument().addDocumentListener(listener);
  76.  
  77.         JPanel contentPane = (JPanel) getContentPane();
  78.         contentPane.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
  79.  
  80.         JPanel panInputLabels = new JPanel(new BorderLayout(0, 5));
  81.         JPanel panInputFields = new JPanel(new BorderLayout(0, 5));
  82.         JPanel panProgressLabels = new JPanel(new BorderLayout(0, 5));
  83.         JPanel panProgressBars = new JPanel(new BorderLayout(0, 5));
  84.  
  85.         panInputLabels.add(lblSource, BorderLayout.NORTH);
  86.         panInputLabels.add(lblTarget, BorderLayout.CENTER);
  87.         panInputFields.add(txtSource, BorderLayout.NORTH);
  88.         panInputFields.add(txtTarget, BorderLayout.CENTER);
  89.         panProgressLabels.add(lblProgressAll, BorderLayout.NORTH);
  90.         panProgressLabels.add(lblProgressCurrent, BorderLayout.CENTER);
  91.         panProgressBars.add(progressAll, BorderLayout.NORTH);
  92.         panProgressBars.add(progressCurrent, BorderLayout.CENTER);
  93.  
  94.         JPanel panInput = new JPanel(new BorderLayout(0, 5));
  95.         panInput.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Input"), BorderFactory.createEmptyBorder(5, 5, 5, 5)));
  96.         JPanel panProgress = new JPanel(new BorderLayout(0, 5));
  97.         panProgress.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Progress"), BorderFactory.createEmptyBorder(5, 5, 5, 5)));
  98.         JPanel panDetails = new JPanel(new BorderLayout());
  99.         panDetails.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Details"), BorderFactory.createEmptyBorder(5, 5, 5, 5)));
  100.         JPanel panControls = new JPanel(new BorderLayout());
  101.         panControls.setBorder(BorderFactory.createEmptyBorder(5, 0, 5, 0));
  102.  
  103.         panInput.add(panInputLabels, BorderLayout.LINE_START);
  104.         panInput.add(panInputFields, BorderLayout.CENTER);
  105.         panProgress.add(panProgressLabels, BorderLayout.LINE_START);
  106.         panProgress.add(panProgressBars, BorderLayout.CENTER);
  107.         panDetails.add(scrollPane, BorderLayout.CENTER);
  108.         panControls.add(btnCopy, BorderLayout.CENTER);
  109.  
  110.         JPanel panUpper = new JPanel(new BorderLayout());
  111.         panUpper.add(panInput, BorderLayout.NORTH);
  112.         panUpper.add(panProgress, BorderLayout.SOUTH);
  113.  
  114.         contentPane.add(panUpper, BorderLayout.NORTH);
  115.         contentPane.add(panDetails, BorderLayout.CENTER);
  116.         contentPane.add(panControls, BorderLayout.SOUTH);
  117.  
  118.         pack();
  119.         setLocationRelativeTo(null);
  120.     }
  121.  
  122.     @Override
  123.     public void actionPerformed(ActionEvent e)
  124.     {
  125.         if("Copy".equals(btnCopy.getText()))
  126.         {
  127.             File source = new File(txtSource.getText());
  128.             File target = new File(txtTarget.getText());
  129.  
  130.             if(!source.exists())
  131.             {
  132.                 JOptionPane.showMessageDialog(this, "The source file/directory does not exist!", "ERROR", JOptionPane.ERROR_MESSAGE);
  133.                 return;
  134.             }
  135.  
  136.             if(!target.exists() && source.isDirectory()) target.mkdirs();
  137.             else
  138.             {
  139.                 int option = JOptionPane.showConfirmDialog(this, "The target file/directory already exists, do you want to overwrite it?", "Overwrite the target", JOptionPane.YES_NO_OPTION);
  140.                 if(option != JOptionPane.YES_OPTION) return;
  141.             }
  142.  
  143.             task = this.new CopyTask(source, target);
  144.             task.addPropertyChangeListener(this);
  145.             task.execute();
  146.  
  147.             btnCopy.setText("Cancel");
  148.         }
  149.         else if("Cancel".equals(btnCopy.getText()))
  150.         {
  151.             task.cancel(true);
  152.             btnCopy.setText("Copy");
  153.         }
  154.     }
  155.  
  156.     @Override
  157.     public void propertyChange(PropertyChangeEvent evt)
  158.     {
  159.         if("progress".equals(evt.getPropertyName()))
  160.         {
  161.             int progress = (Integer) evt.getNewValue();
  162.             progressAll.setValue(progress);
  163.         }
  164.     }
  165.  
  166.     public static void main(String[] args)
  167.     {
  168.         SwingUtilities.invokeLater(new Runnable()
  169.         {  
  170.             @Override
  171.             public void run()
  172.             {
  173.                 new FileCopierUtility().setVisible(true);
  174.             }
  175.         });
  176.     }
  177.  
  178.     class CopyTask extends SwingWorker<Void, Integer>
  179.     {
  180.         private File source;
  181.         private File target;
  182.         private long totalBytes = 0L;
  183.         private long copiedBytes = 0L;
  184.  
  185.         public CopyTask(File source, File target)
  186.         {
  187.             this.source = source;
  188.             this.target = target;
  189.  
  190.             progressAll.setValue(0);
  191.             progressCurrent.setValue(0);
  192.         }
  193.  
  194.         @Override
  195.         public Void doInBackground() throws Exception
  196.         {
  197.             txtDetails.append("Retrieving some info ... ");
  198.             retrieveTotalBytes(source);
  199.             txtDetails.append("Done!\n");
  200.  
  201.             copyFiles(source, target);
  202.             return null;
  203.         }
  204.  
  205.         @Override
  206.         public void process(List<Integer> chunks)
  207.         {
  208.             for(int i : chunks)
  209.             {
  210.                 progressCurrent.setValue(i);
  211.             }
  212.         }
  213.  
  214.         @Override
  215.         public void done()
  216.         {
  217.             setProgress(100);
  218.             btnCopy.setText("Copy");
  219.         }
  220.  
  221.         private void retrieveTotalBytes(File sourceFile)
  222.         {
  223.             File[] files = sourceFile.listFiles();
  224.             for(File file : files)
  225.             {
  226.                 if(file.isDirectory()) retrieveTotalBytes(file);
  227.                 else totalBytes += file.length();
  228.             }
  229.         }
  230.  
  231.         private void copyFiles(File sourceFile, File targetFile) throws IOException
  232.         {
  233.             if(sourceFile.isDirectory())
  234.             {
  235.                 if(!targetFile.exists()) targetFile.mkdirs();
  236.  
  237.                 String[] filePaths = sourceFile.list();
  238.  
  239.                 for(String filePath : filePaths)
  240.                 {
  241.                     File srcFile = new File(sourceFile, filePath);
  242.                     File destFile = new File(targetFile, filePath);
  243.  
  244.                     copyFiles(srcFile, destFile);
  245.                 }
  246.             }
  247.             else
  248.             {
  249.                 txtDetails.append("Copying " + sourceFile.getAbsolutePath() + " ... ");
  250.  
  251.                 BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
  252.                 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile));
  253.  
  254.                 long fileBytes = sourceFile.length();
  255.                 long soFar = 0L;
  256.  
  257.                 int theByte;
  258.  
  259.                 while((theByte = bis.read()) != -1)
  260.                 {
  261.                     bos.write(theByte);
  262.  
  263.                     setProgress((int) (copiedBytes++ * 100 / totalBytes));
  264.                     publish((int) (soFar++ * 100 / fileBytes));
  265.                 }
  266.  
  267.                 bis.close();
  268.                 bos.close();
  269.  
  270.                 publish(100);
  271.  
  272.                 txtDetails.append("Done!\n");
  273.             }
  274.         }
  275.     }
  276. }

Un saludo
__________________
If to err is human, then programmers are the most human of us
  #3 (permalink)  
Antiguo 12/02/2015, 11:00
 
Fecha de Ingreso: junio-2013
Mensajes: 68
Antigüedad: 10 años, 9 meses
Puntos: 1
Respuesta: Hacer ProgressBar

Gracias Profesor_Falken lo voy a probar

Etiquetas: progressbar
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 01:22.