I was doing some reading through the sun java tutorials, and I came across this page here:
Under the heading, “Threads in Applets” I found this piece of code:
//Background task for loading images.
SwingWorker worker = (new SwingWorker<ImageIcon[], Object>() {
public ImageIcon[] doInBackground() {
final ImageIcon[] innerImgs = new ImageIcon[nimgs];
...//Load all the images...
return imgs;
}
public void done() {
//Remove the "Loading images" label.
animator.removeAll();
loopslot = -1;
try {
imgs = get();
} ...//Handle possible exceptions
}
}).execute();
}
First up I’m newish, so I’m sorry if this is a stupid question. However I’ve never heard of that “.excecute()”. I don’t understand it, and I’m unable to find anything about it from google. I see this here is… an anonymous inner class? (Please correct me) and it is starting a thread to load in images. I thought that the run() method is invoked with a call to start()? Please help me clear this confusion.
executeis a method ofSwingWorker. What you’re seeing there is an anonymous class being instantiated and having itsexecutemethod called immediately.I have to admit I’m a bit surprised that code compiles, though, because it seems to be assigning the result of
executeto theworkervariable, and the documentation tells us thatexecuteis avoidfunction.If we deconstruct that code a bit, it can be clearer. First, we create an anonymous class extending
SwingWorkerand create an instance of it, all at the same time (this is the big bit in parentheses):Then we call
executeand assign the result toworker(which is the bit that, it seems to me, shouldn’t compile):Update: And indeed, I tried it and it doesn’t compile. So not great example code. This would compile: