O'Reilly logo

Swing Hacks by Chris Adamson, Joshua Marinacci

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Code Models That Don’t Block #93
Chapter 12, Miscellany
|
465
HACK
in whether you want the Runnable executed immediately or in a few milli-
seconds, and whether you’re willing to handle an
InterruptedException
you can put the code in the worker back on the event-dispatch thread. This
scheme is effectively a callback method, but instead of being concerned
about being called from some event, you’re interested in ensuring you’re
called by a given thread, namely the event-dispatch thread.
In the
doRun( ) implementation, you’ll notice that there’s a flag for whether
or not to use a worker. The blocking version doesn’t, and doesn’t need to,
since it’s already being called from the event-dispatch thread. The non-
blocking version does, but it uses a worker only to reset the contents of the
text area after downloading the contents of the URL:
final StringBuffer finalSBuf = sbuf;
Thread worker = new Thread( ) {
public void run ( ) {
contentArea.setText (finalSBuf.toString( ));
contentArea.setCaretPosition(0);
}
};
SwingUtilities.invokeLater (worker);
Notice how a final variable is used for the StringBuffer.
The anonymous inner thread can see class and instance vari-
ables but not local variables like
sbuf. It can, however, see a
final local variable, so that’s what you pass in.
H A C K
#93
Code Models That Don’t Block Hack #93
Models should know that they’re doing work on another thread.
You already know how to keep Swing responsive by moving expensive oper-
ations off the event-dispatch thread
[Hack #92]. However, one downside to that
approach is that it uses a separate inner class to coordinate the interaction
between the work being done on the other thread and the Swing compo-
nents. If you reused the same widgets in several places, you wouldn’t want
to have to write the “start a thread and populate when done” code over and
over again. So don’t. Why couldn’t the model be responsible for this sort of
behavior?
Well, the model can—you just have to do a little thinking. Models in Swing
are generally in two states:
null (no data) or populated with data. What if
you had a third state, one that indicated that the model was still loading its
data?

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required