[英]Why does my frame freeze when I start this action[DOWNLOADING]
我制作了一个带有“开始下载”按钮的框架,以便从网站上下载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();
}
简短的答案:如果您不想冻结它,则需要在单独的线程上运行它。
有很多实现方法。 几乎所有这些都需要您将addToDestop()方法提取到可运行的类中。 此类可以扩展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
}
}
尝试使用线程,它将停止冻结您的框架
private Thread thread;
。
thread = new Thread(new Runnable(){
public void run(){
//Your code here
}
});
thread.start();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.