The Java Program: SimpleMenu.java
1
2
3
4
5
6
7
8 import java.awt.*;
9 import java.awt.event.*;
10 import java.util.Locale;
11 import java.util.ResourceBundle;
12 import java.util.MissingResourceException;
13
14
15 public class SimpleMenu {
16
17
18 public static Menu create (String bundlename,
19 final String menuname, String[] itemnames) {
20
21 final ResourceBundle b = ResourceBundle.getBundle(bundlename);
22
23 class CommandListener implements ActionListener {
24 public void actionPerformed (ActionEvent e) {
25 String cmd = e.getActionCommand();
26 System.out.println (cmd);
27 System.out.println (b.getString (menuname + "." + cmd + ".label"));
28 }
29 }
30
31 CommandListener theListener = new CommandListener ();
32
33
34 String menulabel;
35 try { menulabel = b.getString(menuname + ".label"); }
36 catch(MissingResourceException e) { menulabel = menuname; }
37
38 Menu m = new Menu(menulabel);
39
40
41 for(int i = 0; i < itemnames.length; i++) {
42
43 String itemlabel;
44 try { itemlabel=b.getString(menuname + "." + itemnames[i] + ".label"); }
45 catch (MissingResourceException e) { itemlabel = itemnames[i]; }
46
47
48 String shortcut;
49 try{shortcut = b.getString(menuname + "." + itemnames[i]+".shortcut"); }
50 catch (MissingResourceException e) { shortcut = null; }
51 MenuShortcut ms = null;
52 if (shortcut != null) ms = new MenuShortcut(shortcut.charAt(0));
53
54
55 MenuItem mi;
56 if (ms != null) mi = new MenuItem(itemlabel, ms);
57 else mi = new MenuItem(itemlabel);
58
59
60 mi.addActionListener (theListener);
61 mi.setActionCommand (itemnames[i]);
62
63
64 m.add(mi);
65 }
66
67
68 return m;
69 }
70
71
72 public static void main(String[] args) {
73
74 if (args.length == 2) Locale.setDefault(new Locale(args[0], args[1]));
75
76 Frame f = new Frame("SimpleMenu Test");
77 MenuBar menubar = new MenuBar();
78 f.setMenuBar(menubar);
79
80
81 Menu colors = SimpleMenu.create ("Menus", "colors",
82 new String[] { "red", "green", "blue" });
83
84 menubar.add(colors);
85 f.setSize(300, 150);
86 f.show();
87 }
88 }