Java Reference
In-Depth Information
Code 11.2
continued
An alternative structure
for the ImageViewer
class
{
super ( "ImageViewer" );
makeFrame();
setVisible( true );
}
/**
* Create the Swing frame and its content.
*/
private void makeFrame()
{
Container contentPane = getContentPane();
JLabel label = new JLabel( "I am a label." );
contentPane.add(label);
pack();
}
}
11.4.4 Adding menus
Our next step toward building a GUI is to add menus and menu items. This is conceptually easy
but contains one tricky detail: How do we arrange to react to user actions, such as the selection
of a menu item? We discuss this below.
First, we create the menus. Three classes are involved:
JMenuBar —An object of this class represents a menu bar that can be displayed below
the title bar at the top of a window (see Figure 11.3). Every window has at most one
JMenuBar . 3
JMenu —Objects of this class represent a single menu (such as the common File, Edit, or
Help menus). Menus are often held in a menu bar. They could also appear as pop-up menus,
but we shall not do that now.
JMenuItem —Objects of this class represent a single menu item inside a menu (such as Open
or Save ).
For our image viewer, we shall create one menu bar and several menus and menu items.
The class JFrame has a method called setJMenuBar . We can create a menu bar and use this
method to attach our menu bar to the frame:
JMenuBar menubar = new JMenuBar();
frame.setJMenuBar(menubar);
3
In Mac OS, the native display is different: the menu bar is at the top of the screen, not the top of each
window. In Java applications, the default behavior is to attach the menu bar to the window. It can be
placed at the top of the screen with Java applications by using a Mac OS-specific property.
 
Search WWH ::




Custom Search