3

I want to use JProgressBar to monitor the progress of copying the contents of a byte array to a JTextArea. In fact, I've read to many tutorials about that but I am still getting a stuck in the following piece of code:

byte[] encodedImg = bOut.toByteArray();
int length = encodedImg.length;
int current = 0;

JProgressBar progressBar = new JProgressBar();
progressBar.setMaximum(length);
progressBar.setValue(0); 

ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int bytesReadSoFar = 0;

while(length  != -1) 
{   
        out.write(buffer); 
        current += bytesReadSoFar;
        textArea.setText(String.valueOf(buffer));
        progressBar.setValue(current);
}

Unfortunately, I still can't get the progress as I want. Could anyone hint me please.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Michael
  • 179
  • 11
  • 1
    You're either block the Event Dispatching Thread or violating the single thread rules of Swing, either way, take a look at [Concurrency in Swing](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/), [Worker Threads and SwingWorker](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/worker.html) – MadProgrammer Jan 16 '15 at 09:00
  • 1
    And [for example](http://stackoverflow.com/questions/16937997/java-swingworker-thread-to-update-main-gui/16938228#16938228) and [example](http://stackoverflow.com/questions/20739488/swingworker-in-multithreaded-jframes/20739571#20739571) and [example](http://stackoverflow.com/questions/13548982/displaying-contents-of-string-array-in-swing-component-as-iterations-using-time/13549338#13549338) – MadProgrammer Jan 16 '15 at 09:02
  • 1
    And [example](http://stackoverflow.com/a/25526869/230513) and [example](http://stackoverflow.com/a/26854330/230513). – trashgod Jan 16 '15 at 09:36
  • 1
    BTW - 1024 bytes? I would be astonished if the JVM took more than a single read to complete the task. Try adding `System.out.println(current);` to the loop. I'll bet you see only one output, and it reads `1024`. But for better help sooner, post an [MCVE](http://stackoverflow.com/help/mcve) (Minimal Complete Verifiable Example) or [SSCCE](http://www.sscce.org/) (Short, Self Contained, Correct Example). – Andrew Thompson Jan 16 '15 at 09:38
  • `int length = encodedImg.length;` I just noticed the loop is testing on `length` but the value of that variable does not change in the body of the loop (suggesting an infinite loop)! ...post an MCVE. – Andrew Thompson Jan 16 '15 at 09:47

1 Answers1

0

I guess that 'current' value should be between 0 to 100, please check that what you're getting there using debug or println

roeygol
  • 4,908
  • 9
  • 51
  • 88