Core Java - [Java Menu]

♠ Posted by Unknown in at 11:10

Create Menu in Java

Menu makes selection easier, and are widely used in window applications. In Java, menus can only appear on a frame. Java provides three classes - MenBar, Menu, and MenuItem - to implements menus in frame.

A frame can hold a menu bar to which the pull-down menus are attached. Menu Consist of menu items that the user can select.

1. To create a Menu bar and associate it with frame.

Frame f = new Frame();
f.setsize(300,300);
f.setVisible(true);

MenuBar mb = new MenuBar();
f.setMenuBar(mb);


2. To Create Menus.
           
             public Menu(String label, boolean tearOff);

In above constructor the "true" tearOff enables the programmer to create a menu that desplays even when the mouse button is released.

            public Menu(String label);

This constructs a new menu instance with the specified label.

            Menu FileMenu = new Menu("File", true);
            mb.add(FileMenu);

3. To Create Menu items:

            FileMenu.add(new MenuItem("New");
            FileMenu.add(new MenuItem("Open");
            FileMenu.add(new MenuItem("-"); To add separator.


Example:

import java.awt.*;
import java.awt.event.*;

public class MyMenuExample extends Frame implements ActionListener
{
            MenuBar mb;
            Menu FileMenu, EditMenu;
           
            public MyMenuExample()
            {
                        mb = new MenuBar();
                        setMenuBar(mb);
                       
                        FileMenu = new Menu("File");
                        EditMenu = new Menu("Edit");
                       
                        mb.add(FileMenu);
                        mb.add(EditMenu);
                       
                        FileMenu.add(new MenuItem("New"));
                        FileMenu.add(new MenuItem("Save"));
                        FileMenu.add(new MenuItem("-"));
                       
                        MenuItem CloseMenuItem = new MenuItem("Close");
                        FileMenu.add(CloseMenuItem);
                        CloseMenuItem.addActionListener(this);
                       
                        EditMenu.add(new MenuItem("Copy"));
                        EditMenu.add(new MenuItem("Paste"));
                       
            }
            public void actionPerformed(ActionEvent ae)
            {
                        dispose();
                        System.exit(0);
            }
           
            public static void main(String[] args)
            {
                        MyMenuExample f = new MyMenuExample();
                        f.setVisible(true);
                        f.setSize(300, 300);
            }
}

1 comments:

Sir plz start .net posting also with java.....

Post a Comment