Search code examples
javaswingfile-uploadjprogressbar

Need help in adding a JProgressBar to a swing application


I am using the following code to upload a file to server using a PUT request. This works properly. But I want to add a JProgressBar to this this code, how do you suggest I do that? I am not sure of which classes to use to achieve the progressbar I need.

RequestEntity re = new RequestEntity() {
    @Override
    public long getContentLength() {
        // TODO Auto-generated method stub
        return file.length();
    }

    @Override
    public String getContentType() {
        // TODO Auto-generated method stub
        return "application/octet-stream";
    }

    @Override
    public boolean isRepeatable() {
        // TODO Auto-generated method stub
        return true;
    }

    @Override
    public void writeRequest(OutputStream outputStream) throws IOException {
        // TODO Auto-generated method stub
        InputStream in = new FileInputStream(file);
        try {
            int l;
            byte[] buffer = new byte[1024];
            while ((l = in.read(buffer)) != -1) {
                outputStream.write(buffer, 0, l);
            }
        } finally {
            in.close();
        }
    }
};

Solution

  • Every time a byte is read, add one to a counter. Provide a method to return the number of bytes total and the number of bytes read. In the GUI code, set the maximum value of the progress bar to the number of bytes, and start a timer that periodically calls progress.setValue with the current number of bytes read.