Java Reference
In-Depth Information
There are several ways to sidestep this paradox, but prior to Java 6 they're all quite
complex. In Java 6 and later, however, the solution is easy. Define a subclass of Swing
Worker and override two methods:
1. The doInBackground() method performs the long-running, I/O-heavy operation.
It does not interact with the GUI. It can return any convenient type and throw any
exception.
2. The done() method is automatically invoked on the event dispatch thread after the
doInBackground() method returns, so it can update the GUI. This method can call
the get() method to retrieve the return value calculated by doInBackground() .
Example 8-8 uses an inner class named Lookup as its SwingWorker . The doInBack
ground() method talks to the whois server, and returns the server's response as a
String . The done() method updates the names text area with the server's response.
The second event this program must respond to is the user typing a new host in the
server text field. In this case, an anonymous inner class tries to construct a new Whois
object and stores it in the server field. If it fails (e.g., because the user mistyped the
hostname), the old server is restored. An alert box informs the user of this event.
This is not a perfect client by any means. The most glaring omission is that it doesn't
provide a way to save the data and quit the program. However, it does demonstrate how
to safely make network connections from a GUI program without blocking the event
dispatch thread.
Search WWH ::




Custom Search