How can we implement right click menu using JPopupMenu in Java?


A JPopupMenu appears anywhere on the screen when a right mouse button is clicked.

JPopupMenu

  • A popup menu is a free-floating menu which associates with an underlying component called the invoker.
  • Most of the time, a popup menu is linked to a specific component to display context-sensitive choices.
  • In order to create a popup menu, we can use the JPopupMenu class., we can add the JMenuItem to popup menu like a normal menu.
  • To display the popup menu, we can call the show() method, normally popup menu is called in response to a mouse event.

Example

import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class JPopupMenuTest extends JFrame {
   private JPopupMenu popup;
   public JPopupMenuTest() {
      setTitle("JPopupMenu Test");
      Container contentPane = getContentPane() ;
      popup = new JPopupMenu();
      // add menu items to popup
      popup.add(new JMenuItem("Cut"));
      popup.add(new JMenuItem("Copy"));
      popup.add(new JMenuItem("Paste"));
      popup.addSeparator();
      popup.add(new JMenuItem("SelectAll"));
      contentPane.addMouseListener(new MouseAdapter() {
         public void mouseReleased(MouseEvent me) {
            showPopup(me); // showPopup() is our own user-defined method
         }
      }) ;
      setSize(375, 250);
      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 JPopupMenuTest();
   }
}

Output

Updated on: 07-Feb-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements