Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
AWT Menu
2.1.
Constructors
2.2.
Functions
3.
AWT MenuBar
3.1.
Constructors
3.2.
Functions
4.
AWT MenuItem
4.1.
Constructors
4.2.
Functions
5.
Example
6.
Frequently Asked Questions
6.1.
What is a Listener?
6.2.
What is the difference between a MenuItem and CheckBoxMenuItem?
7.
Conclusion
Last Updated: Mar 27, 2024

AWT Menu

Author Yashesvinee V
0 upvote
Crack Google SDE interview : Essential projects
Speaker
Saurav Prateek
SDE-2 @
20 Jun, 2024 @ 01:30 PM

Introduction

Java AWT or the Abstract Window Toolkit provides a wide range of options for designing a Graphic User Interface. The java.awt package contains various classes to build components like text fields, checkboxes, radio buttons and many more. A menu is an essential component that helps the user navigate an entire application without difficulty. It can provide links to other parts of the application or display a list of operations that can be performed within the application. Java provides AWT Menu, Menubar and MenuItem components to help set up the features of a typical menu with customisable properties. A Menubar can have many Menus, and each Menu has many MenuItems.

 

Also Read About, Multithreading in java and Hashcode Method in Java

AWT Menu

A Menu object is a pull-down list component that can be accessed from a menu bar. It can contain many MenuItems, each set to perform a particular function. The AWT Menu can be a tear-off menu that can be opened and dragged away from its parent menu bar or menu. The mechanism of a tear-off menu is platform-dependent as the look and feel of the tear-off menu are determined by its peers.

Read More About, Basics of Java

The AWT Menu class inherits methods from java.awt.MenuItem, java.awt.MenuComponent and java.lang.Object.

Signature:

public class Menu
  extends MenuItem
      implements MenuContainer, Accessible

Constructors

AWT Menu has three constructors.

Functions

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

AWT MenuBar

The MenuBar class helps manage the menu bar of a particular frame. The menu bar handles the menu items that are a part of it. It helps set keyboard shortcuts for easy access and passes them along to its child menus. 

Signature:

public class MenuBar
  extends MenuComponent
      implements MenuContainer, Accessible

Constructors

AWT MenuBar has one constructor.

MenuBar() - This creates a new Menu bar.

This class inherits methods from the java.awt.MenuComponent and java.lang.Object.

Functions

You can also read about the Multiple Inheritance in Java.

AWT MenuItem

All the items inside a menu belong to the MenuItem class. Each MenuItem is associated with an ActionEvent that is triggered when the MenuItem is clicked. The processEvent method examines the event and passes it to the processActionEvent function, which redirects the event to any ActionListener objects.

The More Examples MenuItem is a subMenu. The Action Event behaviour is overridden and does not send any event to the frame until any one of its sub-MenuItems is selected.

Signature:

public class MenuItem
  extends MenuComponent
      implements Accessible

Constructors

AWT MenuItem has three constructors.

Functions

Example

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

public class MenuSample 
{
  private Frame mainFrame;
  private Label headerLabel;
  private Label statusLabel;
  private Panel controlPanel;

  public MenuSample()
   {
      MenuGUI();
  }

  public static void main(String[] args)
   {
      MenuSample  ms = new MenuSample();     
      ms.showMenuDemo();
  }

  private void MenuGUI()
   {  
      //create a frame object
      mainFrame = new Frame("Java AWTMenu");
      mainFrame.setSize(400,400);
      mainFrame.setLayout(new GridLayout(3, 1));
      mainFrame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent windowEvent)
         {
            System.exit(0);
        }        
      });    
      headerLabel = new Label();
      headerLabel.setAlignment(Label.CENTER);
      statusLabel = new Label();        
      statusLabel.setAlignment(Label.CENTER);
      statusLabel.setSize(350,100);

      controlPanel = new Panel();
      controlPanel.setLayout(new FlowLayout());

      mainFrame.add(headerLabel);
      mainFrame.add(controlPanel);
      mainFrame.add(statusLabel);
      mainFrame.setVisible(true);  
  }

  private void showMenuDemo()
   {
      //create a menu bar
      final MenuBar menuBar = new MenuBar();

      //create menus
      Menu fileMenu = new Menu("File");
      final Menu aboutMenu = new Menu("About");

      //create menu items
      MenuItem newMenuItem = 
        new MenuItem("New",new MenuShortcut(KeyEvent.VK_N));
      newMenuItem.setActionCommand("New");

      MenuItem openMenuItem = new MenuItem("Open");
      openMenuItem.setActionCommand("Open");

      MenuItem saveMenuItem = new MenuItem("Save");
      saveMenuItem.setActionCommand("Save");

      MenuItem exitMenuItem = new MenuItem("Exit");
      exitMenuItem.setActionCommand("Exit");

      MenuItemListener menuItemListener = new MenuItemListener();

 
      //adding ActionListener
      newMenuItem.addActionListener(menuItemListener);
      openMenuItem.addActionListener(menuItemListener);
      saveMenuItem.addActionListener(menuItemListener);
      exitMenuItem.addActionListener(menuItemListener);
      
      //add menu items to menus
      fileMenu.add(newMenuItem);
      fileMenu.add(openMenuItem);
      fileMenu.add(saveMenuItem);
      fileMenu.addSeparator();
      fileMenu.add(exitMenuItem);

      
      //add menus to menubar
      menuBar.add(fileMenu);
      menuBar.add(aboutMenu);

      //add menubar to the frame
      mainFrame.setMenuBar(menuBar);
      mainFrame.setVisible(true);  
  }

 
   //Setting ActionEvent
  class MenuItemListener implements ActionListener 
   {
      public void actionPerformed(ActionEvent e) 
      {            
        statusLabel.setText(e.getActionCommand() 
            + " MenuItem clicked.");
      }    
  }
}

 

 

Try and compile it by yourself on java online compiler.

The above code creates a MenuBar with two Menu objects - File and About. The File object contains four MenuItems - New, Open, Save and Exit. There is a separator between Save and Exit. On clicking any one of the MenuItems, It displays a Menu Item clicked message. This is the Action Event set to the menu items. The ActionListener listens for the clicking action at the MenuItem and triggers the Action event.

Frequently Asked Questions

What is a Listener?

A listener is an object that gets notified when an event occurs. For this to happen, there are two conditions to be met. First, it must have been registered with a source to receive signals when a specific event occurs. Second, it must implement the necessary methods to receive and process the signals.

What is the difference between a MenuItem and CheckBoxMenuItem?

The MenuItem class is a subclass of MenuComponent, and the CheckboxMenuItem class is a subclass of the MenuItem class. MenuItem only specifies the MenuItem with a name, while CheckBoxMenuItem specifies a MenuItem that can be checked or unchecked.

Conclusion

This article has extensively discussed the AWT Menu, MenuBar and MenuItem classes. We explored the constructors and functions associated with Menu, MenuBar and MenuItem. Lastly, we learnt how to use the three classes to build a MenuBar with menus and menu items in a Java Frame. 

Feeling curious? Coding Ninjas has you covered. Check out our articles on AWT ListAWT PanelAWT LabelDifference between AWT and Swing and JavaFX. Follow our Guided path for Programming in Java here.

Explore our Library on Coding Ninjas Studio to gain knowledge on Data Structures and AlgorithmsMachine LearningDeep LearningCloud Computing and many more! Test your coding skills by solving our test series and participating in the contests hosted on Coding Ninjas Studio! 

Looking for questions from tech giants like Amazon, Microsoft, Uber, etc.? Look at the problems, interview experiences, and interview bundle for placement preparations.

Upvote our blogs if you find them insightful and engaging! Happy Coding!

Previous article
AWT Scrollbar
Next article
What is Sax in XML?
Live masterclass