Java AWT Menu
MenuBar mBar = new MenuBar();
MenuBar object mBar is created and added to the frame. Here, we use setMenuBar() method to add to frame but not add() as MenuBar is not a component. MenuBar is derived from MenuComponent. We know earlier, only components (subclasses of Component) can be added to a container. So, adding a menu bar to frame with add() method raises compilation error. To add, we use a special method setMenuBar(). When added with setMenuBar() method, the menu bar is added to the north side of the frame. Menu bar cannot be added to the other sides of the frame. To applets and panels, menu bar cannot be added.
Menu files = new Menu("Files");
Menu date = new Menu("Date");
Menu exit = new Menu("Exit");
ta = new TextArea(10, 40);
Three Menu objects files, date and exit and one TextArea object ta are created.
All the three Menu objects are added to MenuBar object mBar. Now they will be shown on the menu bar.
MenuItem mi1 = new MenuItem("GLDemo.java");
MenuItem mi1 is created and added to the Menu files. As we do not require the menu item objects in the code, anonymous objects of menu items also can be added as in the above code.
The addSeparator() method adds a pale-colored line between the menu items. With the menu items separator, the menu items can be grouped; it is only for appearance (to make logical groups) but actually they are not grouped and work independently.
ActionListener is registered with the menus and actionPerformed() method is overridden with the event handling code.
char ch = (char) temp;
String s1 = String.valueOf(ch);
TextArea append() method appends each character to the existing with it and requires a string as parameter. So, each integer returned by the read() method is converted into a character and again character is converted into a string and appended. All these conversions are required as append() method requires a string as parameter. The above three lines of code, in realtime, are written as follows.
All the information required by the user is displayed in TextArea as per the menu item selected.
Note: For simplicity in Java AWT Menu, the window closing code is not included. For closing the frame, 4 styles exist and you can apply any one to this program to close the frame. The styles are discussed in "Java Frame Closing – WindowListener".