I use the Java function to download a file from the Internet.
public void getLatestRelease() { try { // Function called long startTime = System.currentTimeMillis(); // Open connection System.out.println("Connecting..."); URL url = new URL(latestReleaseUrl); url.openConnection(); // Download routine InputStream reader = url.openStream(); FileOutputStream writer = new FileOutputStream("release.zip"); byte[] buffer = new byte[153600]; int totalBytesRead = 0; int bytesRead = 0; while ((bytesRead = reader.read(buffer)) > 0) { writer.write(buffer, 0, bytesRead); buffer = new byte[153600]; totalBytesRead += bytesRead; } // Download finished long endTime = System.currentTimeMillis(); // Output download information System.out.println("Done."); System.out.println((new Integer(totalBytesRead).toString()) + " bytes read."); System.out.println("It took " + (new Long(endTime - startTime).toString()) + " milliseconds."); // Close input and output streams writer.close(); reader.close(); } // Here I catch MalformedURLException and IOException :) }
And I have a JProgressBar component in my JPanel , which should visualize the download progress:
private static void createProgressBar(JPanel panel) { JProgressBar progressBar = new JProgressBar(0, 100); progressBar.setValue(0); progressBar.setStringPainted(true); panel.add(progressBar, BorderLayout.SOUTH); }
I would like to separate the "back-end" functions from the "front-end" views presented to users, similar to MVC in web applications.
So, the getLatestRelease() function lies in the framework package in the MyFramework class.
Everything related to the generation of the Swing interface, including event listeners, is in the frontend package.
In the main Controller class, I create an instance of MyFramework and an instance of ApplicationFrontend , which is the main class of the frontend package.
Questions: how to update the progressBar value depending on the progress of the download?
source share