Birdman
Birdman

Reputation: 5424

Prevent application hanging while getting webpage

I have the following code in my swing application:

URL url = new URL("http://stackoverflow.com/");
InputStream is = url.openStream();

But downloading the webpage by using the openStream method makes the swing application hang until the webpage is fully downloaded. How do I prevent this/what are the alternatives, so I can show a loading image until the webpage is fully downloaded?

Upvotes: 2

Views: 106

Answers (2)

Moritz Petersen
Moritz Petersen

Reputation: 13057

Load in a separate thread:

InputStream is = null;

Thread worker = new Thread() {
    // show "loading..."
    public void run() {
        try {
            URL url = new URL("http://stackoverflow.com/");
            is = url.openStream();
        } catch (InterruptedException ex) { ... }
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                // show "done" or remove "loading..."
            }
        });
    }
};
worker.start();

Upvotes: 3

OmniOwl
OmniOwl

Reputation: 5709

You can use multiple threads, which wait for each other.

Upvotes: 3

Related Questions