Java Reference
In-Depth Information
ActionParser
class listed previously to obtain the
Action
objects that represent the
individual menu items in each
JMenu
.
MenuParser
and
MenuBarParser
read menu descriptions from properties files using
a simple grammar illustrated by the following lines from the
WebBr owser-
Resource.properties
file:
# The menubar contains two menus, named "menu.file" and "menu.go"
menubar: menu.file menu.go
# The "menu.file" menu has the label "File". It contains five items
# specified as action objects, and these items are separated into two
# groups by a separator
menu.file: File: action.new action.open action.print - action.close action.exit
# The "menu.go" menu has the label "Go", and contains four items
menu.go: Go: action.back action.forward action.reload action.home
These lines describe a menubar with the property name “menubar” and all its sub-
menus. Note that I've omitted the properties that define the actions contained by
the individual menu panes.
As you can see, the menubar grammar is quite simple: it is just a list of the prop-
erty names of the menus contained by the menubar. For this reason, the
MenuBarParser
code in Example 10-26 is quite simple. The grammar that describes
menus is somewhat more complicated, which is reflected in Example 10-27.
You may recall that the
WebBrowser
example also uses the
GUIResourceBundle
to
read a
JToolBar
from the properties file. This is done using a
ToolBarParser
class.
The code for that class is quite similar to the code for
MenuBarParser
and is not
listed here. It is available in the online example archive, however.
Example 10•26: MenuBarParser.java
package com.davidflanagan.examples.gui;
import javax.swing.*;
import java.util.*;
/**
* Parse a JMenuBar from a ResourceBundle. A menubar is represented
* simply as a list of menu property names. E.g.:
*
menubar: menu.file menu.edit menu.view menu.help
**/
public class MenuBarParser implements ResourceParser {
static final Class[] supportedTypes = new Class[] { JMenuBar.class };
public Class[] getResourceTypes() { return supportedTypes; }
public Object parse(GUIResourceBundle bundle, String key, Class type)
throws java.util.MissingResourceException
{
// Get the value of the key as a list of strings
List menuList = bundle.getStringList(key);
// Create a MenuBar
JMenuBar menubar = new JMenuBar();
// Create a JMenu for each of the menu property names,
// and add it to the bar
int nummenus = menuList.size();