Java Reference
In-Depth Information
this . frame = frame ;
}
@Override
public void run () {
frame . setVisible ( true );
}
}
}
The main() method is the usual block of code to start up a standalone application. It
constructs a Whois object and then uses that to construct a WhoisGUI object. Then the
WhoisGUI() constructor sets up the Swing interface. There's a lot of redundant code
here, so it's broken out into the private methods initSearchFields() , initServer
Choice() , makeSearchInRadioButton() , and makeSearchForRadioButton() . As usual
with LayoutManager -based interfaces, the setup is fairly involved. Because you'd prob‐
ably use a visual designer to build such an application, I won't describe it in detail here.
When the constructor returns, the main() method attaches an anonymous inner class
to the window that will close the application when the window is closed. (This isn't in
the constructor because other programs that use this class may not want to exit the
program when the window closes.) main() then packs and shows the window. To avoid
an obscure race condition that can lead to deadlock this needs to be done in the event
dispatch thread; hence the FrameShower inner class that implements Runnable and the
call to EventQueue.invokeLater() . From that point on, all activity takes place in the
event dispatch thread.
The first event this program must respond to is the user typing a name in the Whois:
search box and either clicking the Find button or hitting Enter. In this case, the Lookup
Names inner class sets the main text to the empty string and executes a SwingWorker to
make the network connection. SwingWorker (introduced in Java 6) is a really important
class to learn if you're going to write GUI applications that access the network, or for
that matter perform any I/O at all.
The problem SwingWorker solves is this. In any Java GUI application there are two rules
you must follow in order to avoid deadlock and slowness:
• All updates to Swing components happen on the event dispatch thread.
• No slow blocking operations, especially I/O, happen on the event dispatch thread.
Otherwise a slow-to-respond server can hang the entire application.
These two rules are at loggerheads for network- and I/O-heavy code because the part
of the code that performs the I/O can't update the GUI and vice versa. These have to
happen in two different threads.
Search WWH ::




Custom Search