How can we create a JPopupMenu with a sub menu in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

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

raja
Published on 24-Jul-2019 13:18:35
Advertisements