Menu Bars
A menu bar is like the main menu bar at the top of the windowed applications to which you are accustomed. Java offers support for menu bars through the JMenuBar class. Table 9 shows the one and only constructor for the JMenuBar class, and Table 10 shows some of the more useful methods for the JMenuBar class.
Table 9. JMenuBar Constructors
Constructor |
Description |
JMenuBar() |
Creates a new menu bar |
Table 10. JMenuBar Methods
Method |
Description |
JMenu add(JMenu) |
Appends the specified menu to the end of the menu bar |
JMenu getMenu(int index) |
Gets the menu at the specified position in the menu bar |
int getMenuCount() |
Returns the number of items in the menu bar |
MenuElement[] getSubElements() |
Returns the menus in this menu bar as an array of MenuElement objects |
Insets getMargin() |
Returns the margin between the menubar's border and its menus |
void setMargin(Insets margin) |
Sets the margin between the menubar's border and its menus |
void setSelected(Component sel) |
Sets the currently selected component, producing a change to the selection model |
You may have use for the various menu management and automation methods in Table 10, but first and foremost, you will use the add method to add JMenu objects to the JMenuBar.
Before we see an example of this, the last method of interest actually resides in the container classes that hold the JMenuBar: it is setJMenuBar(JMenuBar). The setJMenuBar() method adds the specified JMenuBar to the the containing class; for example, the javax.swing.JFrame and the javax.swing.JApplet classes both have a setJMenuBar method. The construction of a JmenuBar is as follows:
public class MyClass extends JFrame { // Build a file menu JMenu menuFile = new JMenu( “File” ); JMenuItem fileOpen = new JMenuItem( “Open”, new ImageIcon( “images/fileOpen.gif” ) ); JMenuItem fileExit = new JMenuItem( “Exit”, new ImageIcon( “images/fileExit.gif” ) ); // Build a help menu JMenu menuHelp = new JMenu( “Help” ); JMenuItem helpContents = new JMenuItem( “Contents” ); JMenuItem helpAbout = new JMenuItem( “About” ); // Create a JMenuBar JMenuBar menuBar = new JMenuBar(); public MyClass() { // Add the file menu to the menu bar menuBar.add( menuFile ); // Build the file menu menuFile.add( fileOpen ); menuFile.addSeparator(); menuFile.add( fileExit ); // Add the help menu to the menu bar menuBar.add( menuHelp ); // Build the help menu menuHelp.add( helpContents ); menuHelp.add( helpAbout ); // set the menu bar to our JFrame setJMenuBar( menuBar ); } }
This listing builds two JMenu objects (each of which contains two JMenuItem objects), adds those to a JMenuBar object, and subsequently sets that JMenuBar as the menu bar for the JFrame.