Working with menus

Working with menus

Posted in : Core Java Posted on : October 29, 2010 at 11:58 AM Comments : [ 0 ]

This section contains the detail about the creating menus using Swing in java.

Working with menus

A menu bar displays a list of top-level menu choices. Each choice is associated with a drop-down menu. A menubar is one of the most visible parts of the GUI application. It is a group of commands located in various menus.

In Java Swing, we use three objects to implement a menubar  :

  • JMenuBar
  • JMenu
  • JMenuItem

Example :

package corejava;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;

public class MenuDemo extends JFrame {
	public MenuDemo() {


	JMenuBar menubar = new JMenuBar();
	ImageIcon icon = new ImageIcon("E:/ankit_tutorial/java/Flags/exit.png");

	JMenu file = new JMenu("File");

	JMenuItem fileClose = new JMenuItem("Close", icon);
	fileClose.setToolTipText("Exit application");
	fileClose.addActionListener(new ActionListener() {
		public void actionPerformed(ActionEvent event) {





	setSize(250, 200);

	public static void main(String[] args) {

		new MenuDemo();



Description of Code

The Following Code create a menubar :

JMenuBar menubar = new JMenuBar();

Below code displays an icon in the menu :

ImageIcon icon = new ImageIcon("exit.png");

The following code creates a menu object and set keyboard shortcut for Menu :

JMenu file = new JMenu("File");

The menus can be accessed via the keybord as well. To bind a menu to a particular key, we use the "setMnemonic" method. In our case, the menu can be opened with the ALT + F shortcut.

We sets the tooltip for menu item as :

fileClose.setToolTipText("Exit application");

Output :

Download Source Code

Go to Topic «PreviousHomeNext»

Your Comment:

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image

Tutorial Topics