Apr 19, 2012

Menu


Java provides two types of menu: pull down and popup menu. Pull down menus are accessed via a menu bar. It may contain many menus. Menu bars may only appear in a frame.

Steps for creating pull down menus

1. Create an object for the MenuBar class
You can attach a MenuBar class to a frame. The menu bar in a window is the horizontal area below the title bar, and contains the caption of each menu.
        MenuBar main=new MenuBar();

2. Attach the menubar to the frame.
You must call the setMenuBar() method to the window to attach the menubar to a frame.
        setMenuBar(main);

3. Create Menu class for each menu you want on the menu bar.
Menu filemenu=new Menu(“File”);
Menu editmenu=new Menu(“Edit”);
Menu helpmenu=new Menu(“Help”);
      The Menu class take a single argument of the menu class that is caption of the menu.

4. Add menu to menubar.
The add() method is called to add each menu object to the menu bar.
main.add(filemenu);
main.add(editmenu);
main.add(helpmenu);

5. Create an Objects for the Menu Item or CheckboxMenuItem class for each sub menu item.
MenuItem new=new MenuItem(“New”);
MenuItem open=new MenuItem(“Open”);
MenuItem close=new MenuItem(“Close”);
MenuItem line=new MenuItem(“-“);
MenuItem exit=new MenuItem(“Exit”);

6. Add the menu item to menu class
filemenu.add(new);
filemenu.add(open);
filemenu.add(close);
filemenu.add(line);
filemenu.add(exit);

Example:

import java.awt.*;

public class MenuDemo {
    public static void main(String[] args)
    {
        Frame f=new Frame("Menu Demo");
        MenuBar main=new MenuBar();
        f.setMenuBar(main);
        Menu filemenu=new Menu("File");
        Menu editmenu=new Menu("Edit");
        Menu helpmenu=new Menu("Help");
        
        main.add(filemenu);
        main.add(editmenu);
        main.add(helpmenu);
        
        MenuItem new1=new MenuItem("New");
        MenuItem open=new MenuItem("Open");
        MenuItem close=new MenuItem("Close");
        MenuItem line=new MenuItem("-");
        CheckboxMenuItem print=new CheckboxMenuItem("Print");
        MenuItem exit=new MenuItem("Exit");
        
        filemenu.add(new1);
        filemenu.add(open);
        filemenu.add(close);
        filemenu.add(line);
        filemenu.add(print);
        filemenu.add(exit);
        
        MenuItem cut=new MenuItem("Cut");
        MenuItem copy=new MenuItem("Copy");
        MenuItem paste=new MenuItem("Paste");
        MenuItem undo=new MenuItem("Undo");
        
        editmenu.add(cut);
        editmenu.add(copy);
        editmenu.add(paste);
        editmenu.addSeparator();
        editmenu.add(undo);
        undo.setEnabled(false);
        
        Menu more=new Menu("More");
        helpmenu.add(more);
        more.add("commands");
        more.add("about");
        
        f.setSize(200, 200);
        f.setVisible(true);
        }

}

Output:





0 comments :

Post a Comment