0

I've tried to receive bytes from a lib to set my JProgressBar update for a long time but unfortunately I didn't get the result I wanted.

The problem is that I don't know how to receive bytes from a lib and how to update the JProgressBar while receiving bytes all that to make a browser with java

This is the code I've tried:

 private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {                                       
   if (evt.getKeyCode() == KeyEvent.VK_ENTER){
       String az = jTextField1.getText();


       if(az.contains("1")){
            String hh = WorkSpace.jTextField1.getText();

     URLConnection conn = null; 
     InputStream in = null;
    try {

      URL url = new URL(hh);
      conn = url.openConnection();
      in = conn.getInputStream();
      int length = conn.getContentLength(); 
      int current = 0;
      WorkSpace.jProgressBar1.setMaximum(length);
      WorkSpace.jProgressBar1.setValue(0);
      byte[] buffer = new byte[1024];
      int numRead = 0;
      while ((numRead = in.read(buffer)) != -1) {
        current=0;
          current += numRead; 
        WorkSpace.jProgressBar1.setValue(current); 

    }

    } catch (Exception e) {

    }
    }

If there's someone who knows how to do this please let me know.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
Ahmed
  • 13
  • 6
  • 2
    Delete ´current=0;´ in while an test again – Gren Dec 12 '14 at 18:16
  • 2
    1- Don't use KeyListener with txt components, use an ActionListerner instead; 2- Swing is single threaded, meaning that any operation which is long running or blocking will prevent the UI from been updated, so even if you do fix the problem with loop, it won't update until the actionPerformed method exits. Instead you could use a SwingWorker – MadProgrammer Dec 12 '14 at 19:11

1 Answers1

2

Just wrap the input stream in a ProgressMonitorInputStream. It will manage its own JProgressBar for you.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • would you mind showing me some code for how to use progressmonitorinput stream please and thank you – Ahmed Dec 13 '14 at 06:06