Java Reference
In-Depth Information
How It Works
The
Sketcher
class has a
SketcherFrame
variable,
window
, as a data member that you use to store the
application window object. You must declare this variable as
static
as there are no instances of the
Sketcher
class around. The
window
variable is initialized in the method
createWindow()
that is called
when the application execution begins on the event dispatch thread. After the
window
object exists, you
set the size of the window based on the screen size in pixels, which you obtain using the
Toolkit
object.
This is exactly the same process that you saw earlier in this chapter. Finally, you call the
setVisible()
method for the window object with the argument
true
to display the application window.
In the constructor for the
SketcherFrame
class, you could pass the title for the window to the superclass
constructor to create the window with the title bar directly. However, later when you have developed
the application a bit more, you should modify the title, so you call the
setTitle()
member to set the
window title here. Next you call the
setJMenuBar()
method that is inherited from the
JFrame
class to
specify
menuBar
as the menu bar for the window. To define the two menus that are to appear on the menu
bar, you create one
JMenu
object with the label
"File"
and another with the label
"Elements"
. These
labels are displayed on the menu bar. You add the
fileMenu
and
elementMenu
objects to the menu bar
by calling the
add()
method for the
menuBar
object.
The
menuBar
field that you have defined represents the menu bar. Both items on the menu bar are of
type
JMenu
and are therefore menus, so you add menu items to each of them. The File menu provides the
file input, file output, and print options, and you eventually use the Elements menu to choose the kind of
geometric figure you want to draw. Developing the menu further, you can now add the menu items.
Adding Menu Items to a Menu
Both menus on the menu bar need menu items to be added — they can't do anything by themselves because
they are of type
JMenu
. You use a version of the
add()
method that is defined in the
JMenu
class to add items
to a menu.
The simplest version of the
add()
method creates a menu item with the label that you pass as an argu-
ment. For example:
JMenuItem newMenu = fileMenu.add("New"); // Add the menu item "New"