Java Reference
In-Depth Information
Image Proxies Reconsidered
At this point, you might ask whether design patterns have helped you. You faithfully
implemented a pattern, and now you're looking at tearing it out. In fact, this is natural and
healthy, although it appears more often in applied development than in topics. An author, with
the help of his or her reviewers, can rethink and replace an inferior design before any reader
sees it. In practice, a design pattern can help you get an application running and can facilitate
the discussion of your design. In the
ImageIconProxy
example at Oozinoz, the pattern has
served its purpose, even though it is much simpler to achieve the effect you desire without a
literal implementation of a proxy.
The
ImageIcon
class operates on an
Image
object. Rather than forwarding painting
requests to a separate
ImageIcon
object, it is easier to operate on the
Image
object that
ImageIcon
wraps. Figure 11.4 shows an
ImageIconLoader
class, from
com.oozinoz.imaging
, that has just two methods beyond its constructor:
load()
and
run()
.
Figure 11.4. The
ImageIconLoader
class works by switching the
Image
object that it
holds.
The
load()
method in this revised class still receives a
JFrame
object to call back after
the desired image is loaded. When
load()
executes, it calls
setImage()
with the image
held by
LOADING
, repaints the frame, and starts a separate thread for itself. The
run()
method, executing in a separate thread, creates a new
ImageIcon
object for the file named
in the constructor, calls
setImage()
with the image held by this object, and repacks
the frame. The almost-complete code for
ImageIconLoader.java
is: