You are on page 1of 7

Enrollment No : 1901160126

Roll No. : 23
Branch : Information Technology
Semester : 5th
Practical No : 05
 Aim: Write a program using AWT to create a menu bar where menu
bar contains menu items such as File, Edit, View and create a
submenu under the File menu: New and Open.
 Program Code
Write a program which creates Menu of different colors and disable
menu item for black color.
import java.awt.*;
class MenuEx extends Frame
{
MenuEx()
{
MenuBar mr=new MenuBar();
setMenuBar(mr);
Menu m1=new Menu("Colours");
MenuItem mn1=new MenuItem("RED");
MenuItem mn2=new MenuItem("YELLOW");
MenuItem mn3=new MenuItem("BLACK");
mn3.setEnabled(false);
MenuItem mn4=new MenuItem("BLUE");
MenuItem mn5=new MenuItem("GREEN");
m1.add(mn1);
m1.add(mn2);
m1.add(mn3);
m1.add(mn4);
m1.add(mn5);
mr.add(m1);
}
}
class MenuBarEx
{
public static void main(String args[])
{
MenuEx m=new MenuEx();
m.setTitle("Menu Bar");
m.setSize(500,500);
m.setVisible(true);
}
}
Output: -
 Practical Related Questions
1. Write the use of setEnabled() method
Answer:
setEnabled() method is used to enable or disable the Menuitem
2. Write the procedure to assign shortcut key to the Menu Item
Answer:  
 JMenuBar − To create a menu bar.
 JMenu − To create a menu.
 JMenuItem − To create a menu item.
 JMenuItem.setMnemonic(KeyEvent.VK_N) − A set a keyboard shortcut to a
menu item.

3. write a syntax and use of addseparator() method.


Answer: 1) public void addSeparator()  - This will append a new separator
to the end of the menu.

2) public void addSeparator(Dimension size)  - This will append


a separator of a specified size to the end of the tool bar.

 Exercise
1. Find errors in following program and display output as shown
below.

import java.awt.*;
import java.awt.event.*;
public class MenuDemo1 extends Frame
{
MenuBar mb;
MenuItem m1,m2,m3,m4;
Menu mn;
MenuShortcut ms;
MenuDemo1()
{
setTitle("MenuBar Demo");
setSize(500,500);
setLayout(null);
ms=new MenuShortcut(KeyEvent.VK_X);
mn=new Menu("File");
mb=new MenuBar();
m1=new MenuItem("New...");
m2=new MenuItem("Open...");
m3=new MenuItem("Save As...");
m4=new MenuItem("Exit",ms);
mn.add(m1);
mn.add(m2);
mn.add(m3);
mn.addSeparator();
mn.add(m4);
mb.add(mn);
}
public static void main(String[] args)
{
MenuDemo1 md=new MenuDemo1();
md.setVisible(true);
}
}

Corrected program:
import java.awt.*;
import java.awt.event.*;
public class MenuDemo1 extends Frame{
MenuBar mb;
MenuItem m1,m2,m3,m4;
Menu mn;
MenuShortcut ms;
MenuDemo1(){
setTitle("MenuBar Demo");
setSize(500,500);
setLayout(null);
mb = new MenuBar();
ms = new MenuShortcut(KeyEvent.VK_X);
mn = new Menu("File");
m1 = new MenuItem("New...");
m2 = new MenuItem("Open...");
m3 = new MenuItem("Save As...");
m4 = new MenuItem("Exit",ms);
mn.add(m1);
mn.add(m2);
mn.add(m3);
mn.addSeparator();
mn.add(m4);
mb.add(mn);
setMenuBar(mb);
}
public static void main(String[] args){
MenuDemo1 md = new MenuDemo1();
md.setVisible(true);
}
}
Output:

You might also like