Ok, I am creating a Java program that is to download mods for the game Minecraft
. I have the following class that does all the downloading and that works fine. But I have an issue where the progress bar does not update whilst the mod is downloading (the whole program freezes whilst downloading)
After much research, other people seem to have the same issue and it can be resolved by using threads.
I just need to know if it is possible to do this using my existing code or do I have to completely re-write my this java class?
package com.anarcist.minemodloader;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.swing.JProgressBar;
public class modsDownloader {
public static Boolean downloadMod(String mod, String saveLoc, JProgressBar progress){
try {
URL url = new URL(mod);
//Set ProgressBar to 0%
progress.setValue((int)0);
//Open the Connection to the file
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//Get filesize
int filesize = connection.getContentLength();
//Start reading at byte 0
float totalDataRead = 0;
BufferedInputStream in = new BufferedInputStream(connection.getInputStream());
FileOutputStream fos = new FileOutputStream(saveLoc);
BufferedOutputStream bout = new BufferedOutputStream(fos, 1024);
byte[] data = new byte[1024];
int i=0;
while((i = in.read(data, 0, 1024)) >= 0){
totalDataRead = totalDataRead + i;
bout.write(data,0,i);
float Percent=(totalDataRead * 100) / filesize;
progress.setValue((int)Percent);
}
bout.close();
in.close();
}catch(Exception e){
javax.swing.JOptionPane.showConfirmDialog((java.awt.Component)
null,e.getMessage(), "Error",
javax.swing.JOptionPane.DEFAULT_OPTION);
}
return true;
}
}
Additionally, this function/class is called using the following code:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
Object selectedObj = modsList.getSelectedValue();
if (selectedObj instanceof modsListItem) {
try {
modsListItem selectedItem = (modsListItem) selectedObj;
System.out.println(selectedItem.getValue());
String fullName = selectedItem.getValue();
String fileParts[] = fullName.split("/");
String fileName = fileParts[fileParts.length - 1];
String saveLoc = config.getModsFolder(true) + "/" + fileName;
modsDownloader.downloadMod(selectedItem.getValue(), saveLoc, jProgressBar1);
} catch (IOException ex) {
Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}
}