Java Reference
In-Depth Information
newItem.addActionListener(actionListener);
file.add(newItem);
ButtonGroup sizeOptions = new ButtonGroup();
JRadioButtonMenuItem smallOption = new JRadioButtonMenuItem("Small (8 x 8, 10 mines)");
smallOption.setMnemonic('s');
smallOption.addActionListener(actionListener);
sizeOptions.add(smallOption);
file.add(smallOption);
JRadioButtonMenuItem mediumOption =
new JRadioButtonMenuItem("Medium (16 x 16, 40 mines)");
mediumOption.setMnemonic('m');
mediumOption.addActionListener(actionListener);
sizeOptions.add(mediumOption);
file.add(mediumOption);
JRadioButtonMenuItem largeOption =
new JRadioButtonMenuItem("Large (16 x 32, 100 mines)");
largeOption.setMnemonic('l');
largeOption.addActionListener(actionListener);
sizeOptions.add(largeOption);
file.add(largeOption);
JMenuItem exitItem = new JMenuItem("Exit");
exitItem.setMnemonic('x');
exitItem.addActionListener(actionListener);
file.add(exitItem);
JMenuBar menuBar = new JMenuBar();
menuBar.add(file);
frame.setJMenuBar(menuBar);
}
The addMenu method is larger than some of the programs we've written so far. As I mentioned at
the start of the chapter, one common complaint about Swing is that it is overly verbose (which means
that it takes a lot of code to do what seems like not much work). Again, that's an unfair criticism because
other user-interface frameworks suffer from the same problem. Being able to set a lot of options to make
your program do all kinds of things means there are a lot of attributes to set, which means a lot of code.
That's the nature of user-interface development. You get used to it after you create a few programs that
have graphical user interfaces (GUIs).
So, let's look at the
addMenu
method in detail. The method follows a repetitious pattern, so we
describe the pattern rather than describe every line (after all, it
is
a big method). The first line creates a
JMenu
object named “file.” If our program also had an Edit menu (such as a word processor might have),
we would have another
JMenu
object. So, to Swing, a menu is one of the menus in the larger menu
structure (which we get to near the bottom of the method). After creating the File menu object, we start
creating
JMenuItem
objects. Each
JMenuItem
object defines one of the choices in this particular menu. For
each menu item, we specify a name (such as “New Game” or “Exit), set a mnemonic character (which
lets the player control the menu with the keyboard), add an
ActionListener
object (the same action
listener for all of them, in this case), and then add the menu item to the file menu object. Towards the
bottom of the method, we create a
JMenuBar
object. A
JmenuBar
object probably corresponds more
closely to what you think of when someone says, “menu,” because a
JMenuBar
object defines the whole
menu across the top of a program. Once we have our
JMenuBar
object, we add the file menu object to it
and, finally, add the whole menu to our window (again, defined by our
JFrame
object).