JPopupMenu Example Java Swing


A JPopupMenu appears anywhere on the screen when a right mouse button is clicked. Following program creates your own popup menu with your choicest menu items.

Here, left mouse click does not generate any event. Popup menu appears on the frame when a right mouse button is clicked and that too at the same point of click.

Example on JPopupMenu
import javax.swing.*;  
import java.awt.event.*;  
import java.awt.*; 

public class JPopupMenuDemo extends JFrame
{
  JPopupMenu popup;

  public JPopupMenuDemo()   
  {
    Container c = getContentPane( ) ;

    popup = new JPopupMenu();
                                         // add menu items to popup
    popup.add(new JMenuItem("undo"));
    popup.add(new JMenuItem("redo"));
    popup.addSeparator();
    popup.add(new JMenuItem("cut"));
    popup.add(new JMenuItem("copy"));
    popup.add(new JMenuItem("paste"));

    c.addMouseListener(new MouseAdapter()   
    {					
      public void mouseReleased(MouseEvent e)  
      {
        showPopup(e);                    // showPopup() is our own user-defined method
      } } ) ;

    setTitle("PopupMenu by S N Rao");
    setSize(300, 300);
    setVisible(true);
  }
  void showPopup( MouseEvent e )  
  {
    if(e.isPopupTrigger())
      popup.show(e.getComponent(), e.getX( ), e.getY());
  }
  public static void main(String args[])
  {
    new JPopupMenuDemo();
  }
}


JPopupMenu
Output screenshot on JPopupMenu Example Java Swing

popup.addSeparator();

addSeparator() method adds a dull colored line in between the menu items. This is useful to separate the items with a common functionality.

e.isPopupTrigger()

Differentiates right click from left mouse click.

e.getX( ), e.getY()

getX() and getY() are the methods of MouseEvent that return the x and y coordinates on the frame where the mouse click takes place.