17.7. Adding a Menu to a Window

As I've already mentioned, a JMenuBar object represents the menu bar that is placed at the top of a window. You can add JMenu or JMenuItem objects to a JMenuBar object, and these will be displayed on the menu bar. A JMenu object is a menu with a label that can display a list of menu items when clicked. A JMenuItem object represents a menu item in a menu, with a label that results in some program action when clicked—such as opening a dialog. A JMenuItem object can have an icon in addition to, or instead of, a String label. Each item on the menu encapsulated in a JMenu object can be an object of either type JMenu, JMenuItem, JCheckBoxMenuItem, or JRadioButtonMenuItem. If an item in a menu is a JMenu object, then it represents a second level of menu containing further menu items.

A JCheckBoxMenuItem is a simple menu item with a checkbox associated with it. The checkbox can be checked and unchecked and typically indicates that that menu item was selected last time the drop-down menu was displayed. You can also add separators in a drop-down menu. These are simply bars to separate one group of menu items from another. A JRadioButtonMenuItem is a menu item much like a radio button in that it is intended to be one of a group of like menu items added to a ButtonGroup object. Both JCheckBoxMenuItem and JRadioButtonMenuItem objects can have icons.

17.7.1. Creating JMenu and JMenuItem

To create a menu you call a JMenu class constructor and pass a String object ...

Get Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.