Way2Java

Java AWT Menu

Menus are very familiar to a programmer in Windows environment. A menu comes with a pull-down list of menu items from which user can select one at a time. When a lot of options in different categories exist to be opted by the user, menus are the best choice as they take less space on the frame. A click on the MenuItem generates ActionEvent and is handled by ActionListener. Java AWT Menu and MenuItem are not components as they are not subclasses of java.awt.Component class. They are derived from MenuComponent class. Following hierarchy illustrates.

Java AWT Menu Hierarchy

Menus creation involves lot of classes like MenuBar, Menu and MenuItem and one is added to the other.

MenuComponent is the super most class of all menu classes; like Component is the super most class for all component classes like Button, Frame etc. MenuBar is capable to hold the menus and Menu can hold menu items. Menus are placed on menu bar.

Steps of Creating Java AWT Menu

Creation of menus involves many steps to be followed in an order. Following are the steps.

  1. Create menu bar
  2. Add menu bar to the frame
  3. Create menus
  4. Add menus to menu bar
  5. Create menu items
  6. Add menu items to menus
  7. Event handling

In the following program, three menus are created and populated with menu items. User's selected menu item information is displayed in the text area.

Example on Java AWT Menu
import java.awt.*;
import java.io.*;
import java.awt.event.*;
public class MenuDemo extends Frame implements ActionListener
{
  TextArea ta;
  public MenuDemo()
  {                      // create menu bar
    MenuBar mBar = new MenuBar();
    setMenuBar(mBar);   // add menu bar to frame
                                // create menus
    Menu files = new Menu("Files");
    Menu date = new Menu("Date");
    Menu exit = new Menu("Exit");
    ta = new TextArea(10, 40);
    ta.setBackground(Color.cyan);
                              // add menus to menu bar
    mBar.add(files);
    mBar.add(date);
    mBar.add(exit);
                             // create menu items to menus
    MenuItem mi1 = new MenuItem("GLDemo.java");
    files.add(mi1);                 // using anonymous menu items
    files.add(new MenuItem("LabelTest.java"));
    files.addSeparator();
    files.add(new MenuItem("UsingFonts.class"));
    files.add(new MenuItem("FLDemo.class"));

    date.add(new MenuItem("Today"));
    exit.add(new MenuItem("Close"));
                               // linking listener
    files.addActionListener(this);
    date.addActionListener(this);
    exit.addActionListener(this);

    add(ta, "Center");
                                          
    setTitle("Menu Practice");
    setSize(400, 400);
    setVisible(true);
  }
  public void actionPerformed(ActionEvent e)
  {
    String str = e.getActionCommand();

    if(str.equals("Close"))
    {
      System.exit(0);
    }
    else if(str.equals("Today"))
    {
      ta.setText("Today: " + new java.util.Date());
    }
    else
    {
      try
      {
        FileReader fr = new FileReader(str);
        ta.setText("Folloiwing are file contents:\n\n");
        int temp;
        while( (temp = fr.read()) != -1)
        {
          char ch = (char) temp;
          String s1 = String.valueOf(ch);
          ta.append(s1);
        }
        fr.close();
      }
      catch(IOException e1)  
      {
        ta.setText("Exception: " + e1);
      }
    }
  }
  public static void main(String args[])
  {
    new MenuDemo();
  }
}


Java AWT Menu

MenuBar mBar = new MenuBar();
setMenuBar(mBar);

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.

mBar.add(files);
mBar.add(date);
mBar.add(exit);

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");
files.add(mi1);
files.add(new MenuItem("LabelTest.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.

files.addSeparator();

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);
ta.append(s1);

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.

ta.append(String.valueOf((char) temp);

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".