一千萬個為什麽

搜索

下載文件時凍結java GUI

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();
        }
    }

在我的其他課程中,我有一個事件監聽器

public void download_buttonActionPerformed(ActionEvent e) {
        download_button.setEnabled(false);
        label_status.setText("- Downloading...");
        download.Download();
    }

When I click the button on my GUI it freezes up and the label & button never change until the file is downloaded:

http://img200.imageshack.us/img200/2435/45019860.png

我是否必須在新線程上開始下載?如果我在一個新線程上啟動它仍然可以使用進度條?我還是java新手,所以如果我這樣做完全錯了,我會道歉。

最佳答案

是的,您需要在單獨的線程上進行下載。實際上,這將允許您使用進度條。

Use a SwingWorker to run the long running task. This tutorial will help with the progress bar: http://download.oracle.com/javase/tutorial/uiswing/components/progress.html

轉載註明原文: 下載文件時凍結java GUI