You are here: Home / Topics / Program to create Menu in AWT in Java

Program to create Menu in AWT in Java

Filed under: Java on 2023-10-25 06:47:10

//  Program to create Menu in AWT.

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

class MyMenu extends Frame implements ActionListener
{
String str="";
CheckboxMenuItem cmiBold , cmiItalic;
MenuItem miNew , miOpen , miSave, miCut, miCopy, miPaste, miRed, miGreen, miBlue;

MyMenu()
{
 super("MyMenu");

 MenuBar mb = new MenuBar() ;
 setMenuBar(mb);
 
 Menu mFile = new Menu("File");
 Menu mEdit = new Menu("Edit");
 Menu mColor = new Menu("Color");
 
 miNew = new MenuItem("New");  
 miOpen = new MenuItem("Open");  
 miSave = new MenuItem("Save");  
 miCut = new MenuItem("Cut");  
 miCopy = new MenuItem("Copy");  
 miPaste = new MenuItem("Paste");  
 miRed = new MenuItem("Red");  
 miGreen = new MenuItem("Green");  
 miBlue = new MenuItem("Blue");  

 cmiBold = new CheckboxMenuItem("Bold");
 cmiItalic = new CheckboxMenuItem("Italic");

 mFile.add(miNew);
 mFile.add(miOpen);
 mFile.add(miSave);
 
 mEdit.add(miCut);
 mEdit.add(miCopy);
 mEdit.add(miPaste);
 mEdit.add(mColor);
 mEdit.add(cmiBold);
 mEdit.add(cmiItalic);
 
 mColor.add(miRed);
 mColor.add(miGreen);
 mColor.add(miBlue);
 
 mb.add(mFile);
 mb.add(mEdit);
 
 miRed.addActionListener(this);
 miGreen.addActionListener(this);
 miBlue.addActionListener(this);
 
 setSize(350,200);
 setVisible(true);

 addWindowListener( new WindowAdapter()
 {
  public void windowClosing( WindowEvent e )
  { 
   System.exit( 0 );
  }
 } );
}

public void actionPerformed(ActionEvent ae)
{
 str = "Selected Color is : ";
 if(ae.getSource() == miRed)
 {
  str += " RED" ;
 }
 else if(ae.getSource() == miGreen)
 {
  str += " GREEN";
 }
 else if(ae.getSource() == miBlue)
 {
  str += " BLUE";
 }
 repaint();
}

public void paint(Graphics g)
{
 g.drawString(str, 150, 75);
 
 if(cmiBold.getState() )
 {
  g.drawString("Bold is ON", 150, 100);
 }
 else 
  g.drawString("Bold is OFF" , 150, 100);
  
 if(cmiItalic.getState() )
 {
  g.drawString("Italic is ON", 150, 125);
 }
 else 
  g.drawString("Italic is OFF", 150, 125);
}
}

public class MenuTest
{
public static void main(String arg[ ])
{
 MyMenu mt = new MyMenu();
}
}

About Author:
J
Java     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.