我制作了一个带有“开始下载”按钮的框架,用于从网站下载 JAR。
问题是每当我点击开始下载按钮时,整个框架就会卡住,直到下载完成,然后就正常了。
Làm thế nào tôi có thể giải quyết vấn đề này?
这是单击按钮时执行的代码
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 {
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
}
}
Tôi là một lập trình viên xuất sắc, rất giỏi!