How To Create Menu Bar IN AWT

Introduction:

In today's article you will learn what a Menu is and how to create a Menu Bar using AWT.

Menu:

Menus are very familiar to a programmers in the Windows environment. A menu has a pull-down list of menu items from which the user can select one at a time. When many options in multiple categories exist for selection by the user, menus are the best choice since they take less space on the frame. A click on the MenuItem generates an ActionEvent and is handled by an ActionListener. A Menu and a MenuItem are not components siince they are not subclasses of the java.awt.Component class. They are derived from the MenuComponent class. The following hierarchy illustrates that.

Menu Hierarchy:

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

menu1.jpg

MenuComponent

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

Procedure for Creating Menus

The following is the procedure for creating menus:

  • Create menu bar
  • Add menu bar to the frame
  • Create menus
  • Add menus to menu bar
  • Create menu items
  • Add menu items to menus
  • Event handling

In the following program, a menu is created and populated with menu items. User's selected menu item or sub-menu item's

  1. import java.awt.*;
  2. class AWTMenu extends Frame
  3. {
  4. MenuBar mbar;
  5. Menu menu,submenu;
  6. MenuItem m1,m2,m3,m4,m5;
  7. public AWTMenu()
  8. {
  9. // Set frame properties
  10. setTitle("AWT Menu"); // Set the title
  11. setSize(300,300); // Set size to the frame
  12. setLayout(new FlowLayout()); // Set the layout
  13. setVisible(true); // Make the frame visible
  14. setLocationRelativeTo(null); // Center the frame
  15. // Create the menu bar
  16. mbar=new MenuBar();
  17. // Create the menu
  18. menu=new Menu("Menu");
  19. // Create the submenu
  20. submenu=new Menu("Sub Menu");
  21. // Create MenuItems
  22. m1=new MenuItem("Menu Item 1");
  23. m2=new MenuItem("Menu Item 2");
  24. m3=new MenuItem("Menu Item 3");
  25. m4=new MenuItem("Menu Item 4");
  26. m5=new MenuItem("Menu Item 5");
  27. // Attach menu items to menu
  28. menu.add(m1);
  29. menu.add(m2);
  30. menu.add(m3);
  31. // Attach menu items to submenu
  32. submenu.add(m4);
  33. submenu.add(m5);
  34. // Attach submenu to menu
  35. menu.add(submenu);
  36. // Attach menu to menu bar
  37. mbar.add(menu);
  38. // Set menu bar to the frame
  39. setMenuBar(mbar);
  40. }
  41. public static void main(String args[])
  42. {
  43. new AWTMenu();
  44. }
  45. }

Sample output of this program:

menu2.jpg

Up Next
    Ebook Download
    View all
    Learn
    View all