I have a program that downloads a file on a button click and I wanted to show the download percentage on a progress bar but the progress bar was not updating and I used a void class for it to not be in the doInBackground method of a swing worker but when I run the code It first downloads the file and after the downloading shows a message and not running the progress bar update method alongside the download method, so I searched google and found out that I could use Threads but When I use the threads It doesn't execute any method in threads. Here is my code with threads:
package mcsm;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import javax.swing.SwingWorker;
import static mcsm.MCSM1.jLabel2;
import static mcsm.MCSM1.jProgressBar1;
public class download {
static SwingWorker sw1 = new SwingWorker() {
@Override
protected String doInBackground() throws Exception {
String fileName = "Hi.jar";
File spigotjar = new File(fileName);
if (!(spigotjar.exists())) {
Thread dlth = new Thread() {
public void rundl() throws Exception {
System.out.println("Downloading !?!");
URL url = new URL("Some URL");
try (InputStream in = url.openStream(); ReadableByteChannel rbc = Channels.newChannel( in ); FileOutputStream fos = new FileOutputStream("Hi.jar")) {
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
URLConnection urlConnection = url.openConnection();
urlConnection.connect();
System.out.println("Wait, thats illegal.");
}
}
};
Thread dlpr = new Thread() {
public void prdl() throws Exception {
dlprogress();
}
};
dlth.start();
dlpr.start();
}
if (spigotjar.exists()) {
Fileexists();
System.out.println("Hey ?!");
}
String res = "Finished Execution";
return res;
}
};
public static void Fileexists() {
jLabel2.setText("The file exists already !");
}
public static void dlprogress() throws Exception {
String fileName = "Hi.jar";
File spigotjar = new File(fileName);
URL url = new URL("Some more URL");
jLabel2.setText("Downloading the file from Bukkit website....");
URLConnection urlConnection = url.openConnection();
int dl_size = urlConnection.getContentLength();
int dlsize_kb = dl_size / 1024;
int dlsize_mb = dlsize_kb / 1024;
long file_sizel = spigotjar.length();
int file_size = (int) file_sizel;
float file_size_kb = file_size / 1024;
float file_size_mb = file_size_kb / 1024;
float total_per_multi = 100 / dlsize_mb;
float percentage = file_size_mb * total_per_multi;
while (file_size != dl_size) {
jProgressBar1.setValue((int) percentage);
System.out.println("Working Fine....");
}
while (file_size == dl_size) {
jProgressBar1.setValue(0);
jLabel2.setText("Download Finished!");
}
}
}
Sorry if its not clear my prime language is not english.