Created
September 26, 2013 06:55
-
-
Save davidsommer/6710695 to your computer and use it in GitHub Desktop.
From http://www.dreamincode.net/forums/topic/162999-java-image-manipulation-part-3-math-and-swingworker/
Loading image Asynchron
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class WebScanner { | |
// These are the variables that hold the URL and the | |
// image when done loading | |
private BufferedImage img; | |
private URL url; | |
// This is a bit more complicated, but I explained it above. | |
private SwingWorker<BufferedImage, Void> worker = new SwingWorker<BufferedImage, Void>() { | |
@Override | |
public BufferedImage doInBackground() { | |
BufferedImage image = null; | |
try { | |
image = ImageIO.read(url); | |
} catch (IOException e) { | |
System.err.println("A loading error occurred"); | |
} | |
return image; | |
} | |
@Override | |
public void done() { | |
try { | |
img = get(); | |
} catch (InterruptedException ignore) {} | |
catch (ExecutionException e) { | |
String why = null; | |
Throwable cause = e.getCause(); | |
if (cause != null) { | |
why = cause.getMessage(); | |
} else { | |
why = e.getMessage(); | |
} | |
System.err.println("A loading error occurred: " + why); | |
} | |
} | |
}; | |
// Sets the URL. Again...using an astronomy picture... | |
public void setURL() { | |
try { | |
url = new URL("http://antwrp.gsfc.nasa.gov/apod/image/1003/mb_2010-03-10_SeaGullThor.jpg"); | |
} catch (MalformedURLException e) { | |
System.err.println("Your tutorial writer wrote down the wrong internet address"); | |
} | |
} | |
// This returns the image when done loading. If there is | |
// a null image, then we retry. | |
public BufferedImage getImage(String fn) { | |
if (img == null) { | |
System.err.println("Attempting again"); | |
// Starts the worker | |
worker.execute(); | |
} | |
return img; | |
} | |
// Access to the worker | |
public void startWorker() { | |
// Starts the worker | |
worker.execute(); | |
} | |
public boolean isWorkerDone() { | |
return worker.isDone(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment