Professional Documents
Culture Documents
In This Chapter
✓ Creating basic menus
✓ Creating dynamic menus
✓ Creating check box menus
I n this chapter, you find out how to adorn your programs with menus.
You've worked with menus in applications, so you're already familiar
with what menus are and how they work, and I don't review those basics in
this chapter. Instead, I jump right into the details of how to create a menu
and add it to a frame.
✦ JMenuBar: This class is the top-level class for menus that appear in the
menu bar at the top of a frame. You can create menus in other ways, but
I focus on this type of menu in this chapter.
✦ JMenu: Each menu in the menu bar is represented by a JMenu object.
The menu bar shown in Figure 3-1 has two JMenu objects: one for the
Game menu and the other for the Options menu.
Figure 3-1:
A frame
with menus.
Then you create one or more menus and add it or them to the menu bar. When
the menu bar is finished, you add it to the frame by calling the setJMenuBar
method:
frame1.setJMenuBar(menuBar);
For your reference, Table 3-1 lists the most useful constructors and methods
of the JMenuBar class.
Creating Menus
To create each menu, you use the JMenu and JMenuItem classes, whose
constructors and methods are shown in the next two tables in this chapter.
Start by calling the JMenu constructor and giving a name to the menu:
Next, set the mnemonic shortcut key that the user can use to get at the menu
without touching the mouse. If you want the letter G to be the mnemonic, use
this statement:
gameMenu.setMnemonic('G');
Here the letter G is underlined, and the user can access the menu by press-
ing Alt+G. Notice that the mnemonic character is passed as a character
literal, not a string literal. Table 3-2 lists the most important constructors
and methods of the JMenu class for your reference.
At first glance, this code seems like a nice time-saver. Unfortunately, it doesn't
let you create the mnemonic shortcut key for the menu item, so you're better
off using the JMenuItem constructor and then using the JMenu add method
to add the item to the menu, as in this example:
This code creates a menu item that displays the text New Game, which the
user can access by pressing N after the Game menu is activated. (The N key
is a shortcut.)
If the menu text contains more than one occurrence of the mnemonic char-
acter, and you want a character other than the first one to be underlined,
you have to call the setDisplayedMnemonicIndex method and specify
the index number of the character you want to underline, as in this example:
You can call the addSeparator method of the JMenu class to add a separa-
tor between menu elements. Here's a sequence of statements that creates
the menu shown in Figure 3-1 earlier in this chapter:
For more information about Lambda expressions, refer to Book III, Chapter 7.
Here's a simple example that exits the program if the event source is a menu
item named exitItem:
To use this listener, pass it via a Lambda expression to the exit menu item's
addActionListener method, as follows:
If you prefer, you can eliminate the exitItemAction method altogether and
call System.exit directly in the addActionLIstener method, like this:
A common way to handle action events for a menu is to use a single method to
handle events for all of the menu items in the menu. To do that, you must pass
the ActionEvent object to the event handler method via the Lambda expres-
sion when you call the addActionListener method, as in this example:
Here's a sample action listener that you may want to use while you're learn-
ing how to work with menus. It simply displays the text of each menu item
on the console whenever the user chooses a menu command. That way, you
can be certain you're setting up your menus and action listeners properly:
You may want the Pause Game menu item in the Game menu to change to
Resume Game when the user pauses the game, for example. Then, if the user
resumes the game, this menu item reverts to Pause Game. You could do that
in several ways. The easiest is to just look at the text in the menu item. If the
text is Pause Game, change it to Resume Game; if the text is Resume Game,
change it to Pause Game. Here's a snippet of code that does the job:
if (pauseItem.getText().equals("Pause Game"))
{
pauseItem.setText("Resume Game");
pauseItem.setMnemonic('R');
}
else
{
pauseItem.setText("Pause Game");
pauseItem.setMnemonic('P');
}
This code also sets the mnemonic letter. In a real program, of course, this
code also pauses and resumes the game.
if (pauseItem.getText().equals("Pause Game"))
{
pauseItem.setText("Resume Game");
pauseItem.setMnemonic('R');
quitItem.setEnabled(false);
}
else
{
pauseItem.setText("Pause Game");
pauseItem.setMnemonic('P');
quitItem.setEnabled(true);
}
Figure 3-2:
A menu with
check box
menu items.
To create a check box menu item, you use the JCheckBoxMenuItem class,
whose constructors and methods are listed in Table 3-4. This class inherits
the JMenuItem class, so most of its methods are the same. You can specify
the state of the check box when you call the JCheckBoxMenuItem
constructor, or you can allow it to default to false.
Constructor Description
void setDisplayedMnemonicIndex Sets the index of the mnemonic
(int index) character to be underlined. You
need to use this method only if
you don't want the first occur-
rence of the character specified
by the setMnemonic method
to be underlined.
void setEnabled(boolean value) Enables or disables the menu
item.
void setMnemonic(int char) Sets the mnemonic key. The
character is usually passed as a
character literal.
void setState(boolean value) Sets the state of the check box.
void setText(String text) Sets the menu item's text.
To test the state of the check box, you use the getState method, as in this
example:
if (musicItem.getState() == true)
System.out.println(
"Your mamma can't dance.");
else
System.out.println(
"Your daddy can't rock and roll.");
Here two different messages are displayed on the console, depending on the
setting of the check box for the musicItem menu item.
public GameMenu()
{
this.setSize(600,400);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setJMenuBar(buildMenu()); ➝19
this.setVisible(true);
}