开发者

java GUI frozen when downloading file

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

In my other class I have a event listener

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

Do I have to start the download on a new thread or something? If I start it on a new thread is it still possible to use the progress bar? I'm still new to java so I apologize if I'm doing this completely wrong.


Yes you need to do the download on a separate thread. In fact that will allow you to use a progress bar.

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


This is Java Swing programming 101. When you do tasks that take a long time, you MUST do these tasks in a different thread. Otherwise, your UI thread will pause and not dispatch any events until the task is done. Take a look at SwingWorker. This is how you can create threads and update UI when something changes.


Do I have to start the download on a new thread or something?

Yes. A SwingWorker would be perfect for this.

If I start it on a new thread is it still possible to use the progress bar?

Yes. Have you gone through the Swing tutorial covering progress bars? It will show how to use these with sample code.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜