Java Reference
In-Depth Information
EXAMPLE:
(continued)
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. How-
ever, it makes more sense to use the anonymous object
new
EndingListener()
since
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 applica-
tion program. However, in normal situations, the application program knows when the win-
dow 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).
Display 17.4
The Normal Way to Define a
JFrame
(part 1 of 2)
1
import
javax.swing.JFrame;
2
import
javax.swing.JButton;
3
public class
FirstWindow
extends
JFrame
4{
5
public static final int
WIDTH = 300;
6
public static final int
HEIGHT = 200;
7
public
FirstWindow()
8
{
9
super
();
10
setSize(WIDTH, HEIGHT);
11
setTitle("First Window Class");
(continued)