Java Reference
In-Depth Information
public static void display(Component c, String title)
{
JFrame f = new JFrame(title);
f.getContentPane().add(c);
f.addWindowListener
(
new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
);
f.pack();
f.setVisible(true);
}
In Chapter 4, Facade, you will port this code to a utility class. With fewer than 20 statements
of its own, the
ShowRocketTable
class sits above hundreds or thousands of statements that
collaborate to produce a table component within a GUI framework. The
JTable
class can
handle nearly every aspect of displaying a table, but it can't know in advance what data you
will want to present. To let you supply the data it needs, the
JTable
class sets you up to
apply A
DAPTER
. To use
JTable
, you implement the
TableModel
interface that
JTable
expects, along with a class that provides the data you want to display.
It's easy to use
JTable
because this class is designed for adaptation. In practice, when you
need to adapt an existing class to meet a client's needs, you may find that the client code
designers have not foreseen this possibility and have not provided an interface to adapt to.
Unforeseen Adaptation
Suppose that an existing application at Oozinoz issues warnings and prints out other messages
to
System.out
. The commonly used expression
System.out
is an instance of
PrintStream
. Noting this and foreseeing that you might want to redirect the message
output, the application's designers have built in a
setOutput()
method. It would be better if
these designers had defined the interface they required for displaying messages. That would
have let you provide an implementation for just the
PrintStream
methods that the
application uses. But at least the
setOutput()
method lets you supply a different instance
of
PrintStream
as the message channel.
Suppose that you want to redirect the messages to appear in a
JText-Area
object.
Inspecting the application, you note that the only call it makes to the
PrintStream
object
you supply is
print()
, with an
Object
argument. To redirect these
print()
calls to
a
JTextArea
object, you might design the
MessageAdapter
class as shown in Figure 3.8.