我用一个按钮做了一个框架"开始下载"它可以从网站下载JAR。
问题是每当我点击开始下载按钮时,整个框架都会冻结,直到完成下载,然后它就会正常。
我该如何解决?
这里是单击按钮执行时的代码
private void addToDesktop() throws IOException {
URL url = new URL("urlremoved");
URLConnection connection = url.openConnection();
InputStream inputstream = connection.getInputStream();
FileSystemView filesys = FileSystemView.getFileSystemView();
filesys.getHomeDirectory();
sizeOfClient = connection.getContentLength();
BufferedOutputStream bufferedoutputstream = new BufferedOutputStream(new FileOutputStream(new File(clientDL.textField1.getText() + "/jarname.jar")));
byte[] buffer = new byte[2048];
int length;
while(( length = inputstream.read(buffer)) > -1)
{
down += length;
bufferedoutputstream.write(buffer, 0 , length);
String text = clientDL.label1.getText();
int perc = getPerc();
if(perc <= 50)
{
text += getPerc() + "% done";
}else
{
text ="Please wait until the jar is downloading...";
text = text + (100 - perc) + " % remaining";
}
}
if (down == sizeOfClient) {
JOptionPane.showMessageDialog(clientDL.frame, "Download successful. It has been placed at : " + clientDL.textField1.getText() + "/jarname.jar", "Success!", JOptionPane.INFORMATION_MESSAGE);
clientDL.frame.dispose();
clientDL.frame.setVisible(false);
}
bufferedoutputstream.flush();
bufferedoutputstream.close();
inputstream.close();
hideSplashScreen();
}
答案 0 :(得分:2)
简短回答:如果你不希望它冻结,你需要在一个单独的线程上运行它。
有很多方法可以实现这一点。几乎所有都要求您将addToDestop()方法提取到runnable类中。这个类可以扩展Thread或SwingWorker或任何那种性质。
您可以查看SwingWorker的以下链接。
http://www.oracle.com/technetwork/articles/javase/swingworker-137249.html
遵循伪代码会给你一个想法。
public class Downloader extends SwingWorker<VOID, VOID> {
private String url;
public Downloader(String url){
this.url = url;
}
private void addToDesktop(){
//your code
}
@override
protected void doInBackground(){
addToDesktop();
}
@override
protected void done(){
//success
}
}
答案 1 :(得分:0)
尝试使用Threads它会停止冻结你的框架
private Thread thread;
thread = new Thread(new Runnable(){
public void run(){
//Your code here
}
});
thread.start();