Creating a Menu with I18N Resources

Problem

You want to internationalize an entire Menu.

Solution

Get the Menu’s label, and each MenuItem’s label, from a ResourceBundle.

Discussion

Fetching a single menu item is the same as fetching a button:

rb = getResourceBundle("Widgets");
try { label = rb.getString("exitMenu.label"); }
catch (MissingResourceException e) { label="Exit"; } // fallback
someMenu.add(new JMenuItem(label));

This is a lot of code, so we typically consolidate it in convenience routines (see Section 14.5). Here is sample code, using our convenience routines:

JMenu fm = mkMenu(rb, "file");
fm.add(mkMenuItem(rb, "file", "open"));
fm.add(mkMenuItem(rb, "file", "new"));
fm.add(mkMenuItem(rb, "file", "save"));
fm.add(mkMenuItem(rb, "file", "exit"));
mb.add(fm);
Menu um = mkMenu(rb, "edit");
um.add(mkMenuItem(rb, "edit", "copy"));
um.add(mkMenuItem(rb, "edit", "paste"));
mb.add(um);

Get Java Cookbook 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.