korek
korek

Reputation: 113

Remaiming file size counter

I'm trying to make a progress bar or something like that in my program that is sending files to a server. I've this

ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());  
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());  

oos.writeObject(file.getName());  

FileInputStream fis = new FileInputStream(file);  
byte [] buffer = new byte[Server.BUFFER_SIZE];  
Integer bytesRead = 0;  
jj = size-bytesRead;
int i = 0;

while ((bytesRead = fis.read(buffer)) > 0) {  
     oos.writeObject(bytesRead);  
     jButton3.doClick();
     oos.writeObject(Arrays.copyOf(buffer, buffer.length));  
}  
oos.close();  
ois.close();  

And this is Button3

temp = temp - 100;
jLabel3.setText(String.valueOf(temp));

temp is a size of chosen file and I'm subtracting 100 because it's the size of bytes in every step in the loop.

The problem is when I start sending file, Button3 is grayed till the end of sending doing nothing visible with label (like it is too slow to update the label on time) but at the end it's displaying a right data.

Why it can't periodically update the label? What should I do to fix that? Thanks for any advice.

Upvotes: 0

Views: 51

Answers (1)

Mark Peters
Mark Peters

Reputation: 81074

You're probably doing the I/O on the Event Dispatch Thread, which is preventing the UI from processing its normal paint events. If you have a long-running operation, you shouldn't be doing it on the EDT (e.g. by doing it in an listener like ActionListener for a button click).

You need to do this work in a background thread and send updates to the UI. An easy way to do that is to use SwingWorker. Put the long-running code in doInBackground(). Call publish(byteCount) when you read some byteCount bytes. And then in process() update the progress bar.

Here's an example of SwingWorker that updates a JProgressBar: java update progressbar

Upvotes: 2

Related Questions