Java Reference
In-Depth Information
EXAMPLE:
(continued)
Similarly, the method invocations
setDefaultCloseOperation(
JFrame.DO_NOTHING_ON_CLOSE);
and
add(endButton);
are equivalent to
this
.setDefaultCloseOperation(
JFrame.DO_NOTHING_ON_CLOSE);
and
this
.add(endButton);
In the class
FirstWindow
( Display 17.4 ), we added the title
"First Window Class"
to the window as follows:
setTitle("First Window Class");
You can see where the title is displayed in a
JFrame
by looking at the picture of the
GUI given in Display 17.4 .
One thing we did differently in Display 17.4 than in Display 17.2 is to use an
anonymous object in the following line:
endButton.addActionListener(
new
EndingListener());
The same action was performed by the following lines in Display 17.2:
EndingListener buttonEar =
new
EndingListener();
endButton.addActionListener(buttonEar);
In Display 17.2, we were trying to be extra clear and so we used these two steps.
However, it makes more sense to use the anonymous object
new EndingListener()
because this listener object is never referenced again and so does not need a name.
The program
DemoWindow
in Display 17.4 simply displays an object of the class
FirstWindow
on the screen.
Almost all of the initialization details for the window in Display 17.4 have been
moved to the constructor for the class
FirstWindow
. However, we have placed the
invocations of the method
setVisible
in the application program that uses the
window class
FirstWindow
. We could have placed an invocation of
setVisible
in
the constructor for
FirstWindow
and omitted the invocation of
setVisible
from the
application program
DemoWindow
(Display 17.4). If we had done so, we would have
produced the same results when we ran the application program. However, in normal
situations, the application program knows when the window should be displayed,
so it is normal to put the invocation of the method
setVisible
in the application
program. The programmer writing the class
FirstWindow
cannot anticipate when a
programmer who uses the window will want to make it visible (or hide it).