Java Reference
In-Depth Information
Example 10•25: ActionParser.java (continued)
public Object parse(GUIResourceBundle bundle, String key, Class type)
throws java.util.MissingResourceException
{
// Look up the Action cache associated with this bundle
HashMap cache = (HashMap) bundleToCacheMap.get(bundle);
if (cache == null) { // If there isn't one, create one and save it
cache = new HashMap();
bundleToCacheMap.put(bundle, cache);
}
// Now look up the Action associated with the key in the cache.
Action action = (Action) cache.get(key);
// If we found a cached action, return it.
if (action != null) return action;
// If there was no cached action create one. The command is
// the only required resource. It will throw an exception if
// missing or malformed.
Command command = (Command) bundle.getResource(key, Command.class);
// The remaining calls all supply default values, so they will not
// throw exceptions, even if ResourceParsers haven't been registered
// for types like Icon and KeyStroke
String label = bundle.getString(key + ".label", null);
Icon icon = (Icon) bundle.getResource(key + ".icon", Icon.class, null);
String tooltip = bundle.getString(key + ".description", null);
KeyStroke accelerator =
(KeyStroke) bundle.getResource(key + ".accelerator",
KeyStroke.class, null);
int mnemonic = bundle.getInt(key + ".mnemonic", KeyEvent.VK_UNDEFINED);
boolean enabled = bundle.getBoolean(key + ".enabled", true);
// Create a CommandAction object with these values
action = new CommandAction(command, label, icon, tooltip,
accelerator, mnemonic, enabled);
// Save it in the cache, then return it
cache.put(key, action);
return action;
}
}
Parsing Menus
We've seen that the GUIResourceBundle class makes it easy to read simple GUI
resources, such as colors and fonts, from a properties file. We've also seen how to
extend GUIResourceBundle to parse more complex resources, such as Action
objects. Fonts, colors, and actions are resources that are used by the components
that make up a GUI. With a small conceptual leap, however, we can start to think
of GUI components themselves as resources to be used by the larger application.
Example 10-26 and Example 10-27 show how this can work. These examples list
the MenuBarParser and MenuParser classes, which read JMenuBar and JMenu
objects, respectively, from a properties file. MenuBarParser relies on MenuParser to
obtain the JMenu objects that populate the menubar, and MenuParser relies on the
Search WWH ::




Custom Search