Java Reference
In-Depth Information
menuBar.add(elementMenu); // Add the element
menu
}
// File menu items and the rest of the class as before...
}
Directory "Sketcher 4 with shortcuts and accelerators"
If you save
SketcherFrame.java
after you have made the changes, you can recompile Sketcher and run
it again. The file menu now appears as shown in
Figure 17-39
.
How It Works
You have added a static
import
statement for the constants in the
InputEvent
class. The names of the
constants are already quite wordy and importing the names saves having to add qualifiers to them.
You use the
setMnemonic()
method to set the shortcuts for the menu bar items, and the
setAccelerat-
or()
method to add accelerators to the submenu items. You must make sure that you do not use duplicate
key combinations, and the more menu items that you have accelerators for, the trickier this gets. The File
menu here defines the standard Windows accelerators. You can see that the
setAccelerator()
method
adds the shortcut key combination to the item label.
The menus don't actually work at the moment, but at least they look good! You start adding the code to
implement menu operations in the next chapter.
SUMMARY
In this chapter you learned how to create an application window and how to use containers in the creation
of the GUI for a program. You also learned about the primary layout managers for arranging components
within a container. You know how to create menus in a menu bar, and how you define drop-down menus.