Java Reference
In-Depth Information
Dimension wndSize = theKit.getScreenSize(); // Get screen size
// Set the position to screen center & size to half screen size
window.setBounds(wndSize.width/4, wndSize.height/4, // Position
wndSize.width/2, wndSize.height/2); // Size
window.setVisible(true);
}
}
Save this file as Sketcher.java in the Sketcher directory. If you compile and run Sketcher you
should see the window shown.
How It Works
The Sketcher class has a SketchFrame variable as a data member, which we will use to store the
application window object. We must declare this variable as static as there will be no instances of the
Sketcher class around. The variable, window , is initialized in the method main() that is called when
program execution begins. Once the window object exists, we set the size of the window based on the
screen size in pixels, which we obtain using the Toolkit object. This is exactly the same process that
we saw earlier in this chapter. Finally in the method main() , we call the setVisible() method for
the window object with the argument true to display the application window.
In the constructor for the SketchFrame class, we could pass the title for the window to the superclass
constructor to create the window with the title bar directly. However, later when we have developed the
application a bit more we will want to add to the title, so we call the setTitle() member to set the
window title here. Next we 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, we create one JMenu object with the label " File " and another with the label " Elements " -
these labels will be displayed on the menu bar. We add the fileMenu and elementMenu objects to
the menu bar by calling the add() method for the menuBar object.
The instance variable that we have defined in the SketchFrame class represents the menu bar. Both
the menu items on the menu bar are of type JMenu , so we need to add pull-down menus to each of
them. The File menu will provide the file input, output, and print options, and we will eventually use
the Elements menu to choose the kind of geometric figure we want to draw. Developing the menu
further, we can now add the menu items.
Search WWH ::




Custom Search