![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How can we create a JPopupMenu with a sub menu in Java?
A JPopupMenu is a subclass of JComponent class and it can appear anywhere on the screen when a right mouse button is clicked. In order to create a popup menu, we can use the JPopupMenu class. In general, we can add the menu items to a JPopupMenu and also add a submenu to JPopupMenu by adding the menu items to submenu first then add it to JPopupMenu. A Popup menu is triggered by mouse events, so we need to register a MouseListener interface. We can override the mouseReleased() method to display the popup menu when we get an appropriate event by calling isPopupTrigger() method and display it by calling its show() method with the mouse event coordinates as arguments.
Example
import java.awt.event.*; import java.awt.*; import javax.swing.*; public class JPopupMenuwithSubMenuTest extends JFrame { private JPopupMenu popup; private JMenu subMenu; public JPopupMenuwithSubMenuTest() { setTitle("JPopupMenuwithSubMenu Test"); popup = new JPopupMenu(); subMenu = new JMenu("Course"); subMenu.add("Java"); subMenu.add("Python"); subMenu.add("Scala"); popup.add(new JMenuItem("First Name")); popup.add(new JMenuItem("Last Name")); popup.addSeparator(); popup.add(subMenu); addMouseListener(new MouseAdapter() { public void mouseReleased(MouseEvent me) { showPopup(me); } }) ; setSize(400, 275); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } void showPopup(MouseEvent me) { if(me.isPopupTrigger()) popup.show(me.getComponent(), me.getX(), me.getY()); } public static void main(String args[]) { new JPopupMenuwithSubMenuTest(); } }
Output
Advertisements