Kyl*_*yle 1 java user-interface swing multithreading swingworker
public class download {
public static void Download() {
final String saveTo = System.getProperty("user.home").replace("\\", "/") + "/Desktop/";
try {
URL url = null;
url = new URL("http://cachefly.cachefly.net/10mb.test");
ReadableByteChannel rbc = Channels.newChannel(url.openStream());
FileOutputStream fos = new FileOutputStream(saveTo + "10mb.test");
fos.getChannel().transferFrom(rbc, 0, 1 << 24);
} catch (Exception e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
在我的其他课程中,我有一个事件监听器
public void download_buttonActionPerformed(ActionEvent e) {
download_button.setEnabled(false);
label_status.setText("- Downloading...");
download.Download();
}
Run Code Online (Sandbox Code Playgroud)
当我点击我的GUI上的按钮时,它会冻结,标签和按钮永远不会改变,直到文件被下载:
http://img200.imageshack.us/img200/2435/45019860.png
我是否必须在新线程上开始下载?如果我在一个新线程上启动它仍然可以使用进度条?我还是java的新手,所以如果我这样做完全错了,我会道歉.
是的,您需要在单独的线程上进行下载.实际上,这将允许您使用进度条.
使用SwingWorker运行长时间运行的任务.本教程将对进度条提供帮助:http://download.oracle.com/javase/tutorial/uiswing/components/progress.html