Java Reference
In-Depth Information
About half of the methods in PlaceATub_1 exist to lazy-initialize variables that contain
the application's components. The textField() method is typical:
public JTextField textField()
{
if (textField == null)
{
textField = new JTextField();
textField.setFont(font());
textField.addActionListener(this);
textField.addFocusListener(this);
}
return textField;
}
Most of the remaining methods in PlaceATub contain logic that handles the application's
events. The focusGained() and focusLost() methods, for example, manage the effects
of the user's tabbing in and out of the text field:
public void focusGained(FocusEvent e)
{
textField.selectAll();
}
public void focusLost(FocusEvent e)
{
textFieldChanged();
}
The textFieldChanged() method updates the affected machine and tub objects.
Note that the M EDIATOR pattern is at work in this class. Components don't update one another
directly; rather, they issue events that a class can register for and react to. A PlaceATub_1
object encapsulates how the components in a GUI interact. The mechanics of Swing nudge
you into using a mediator, although nothing in Swing suggests that an application must be its
own mediator.
Instead of mingling component-creation methods with event-handling methods in one class,
you can move all event handling into a separate mediator class. This refactoring results in
a pair of simpler classes, with two specializations: component creation and event handling.
Search WWH ::




Custom Search