Home Java Example Java Swing Create a Popup Menus with Nested Menus in Java



Create a Popup Menus with Nested Menus in Java
Posted on: April 14, 2007 at 12:00 AM
In this section, you will learn how to create a nested popup menu in Java Swing.

Create a Popup Menus with Nested Menus in Java

     

In this section, you will learn how to create a nested popup menu in Java Swing. When you click the right mouse button on the frame then you get a popup menu. Here, you will show multiple menu items like: line up icon, refresh, properties and new in the list of the menu which represents the popup menu. The new menu item have another popup menu which contains items like: folder, text document and shortcut. Following figure shows the nested popup menu:

Nested Pop Up Menu in Swing Application

createMenu(String):
This method has been used to create a nested list of menus for the 'New' menu item from the main popup menu list. 

Here is the code of program:

import javax.swing.*;
import java.awt.event.*;

public class NestedPopupMenu{
  JPopupMenu Pmenu;
  JMenuItem Mitem;
  public static void main(String[] args) {
  NestedPopupMenu n = new NestedPopupMenu();
  }

  public  NestedPopupMenu(){
  JFrame frame = new JFrame("Creating a Popup Menu with Nested Menus");
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  Pmenu = new JPopupMenu();
  Mitem = new JMenuItem("Line Up Icon");
  Pmenu.add(Mitem);
  Mitem = new JMenuItem("Refresh");
  Pmenu.add(Mitem);
  Mitem = new JMenuItem("Properties");
  Pmenu.add(Mitem);
  Pmenu.add(createMenu("New"));
  frame.addMouseListener(new MouseAdapter(){
  public void mouseReleased(MouseEvent Me){
  if(Me.isPopupTrigger()){
  Pmenu.show(Me.getComponent(), Me.getX(), Me.getY());
  }
  }
  });
  frame.setSize(400,400);
  frame.setVisible(true);
  }

  public JMenu createMenu(String title){
  JMenu m = new JMenu(title);
  m.add("Folder");
  m.add("Text Document");
  m.add("Shortcut");
  return m;
  }
}

Download this example

Related Tags for Create a Popup Menus with Nested Menus in Java:
javacswinglistpropertiesbuttoniomenumousestructmultiplepopupgetnestedconstrefreshiconipclicknewclilinethislikeframeshowietorameachrefsheilititemitemsmultisectionliuseulpepopinmnttrjclesememsicomehowprotierightwhenwhichstipkisllproperpreeaandconsstrreprrtropewingvattssriteateachthshoswavstframiplpleplpropprndono


More Tutorials from this section

Ask Questions?    Discuss: Create a Popup Menus with Nested Menus in Java  

Post your Comment


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

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.