Java Swing How to - Create a Popup Menu








Question

We would like to know how to create a Popup Menu.

Answer

// ww  w  . ja  v a2s  .  c om
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JButton;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;

public class Main {
  public static void main(String[] argv) throws Exception {
    final JPopupMenu menu = new JPopupMenu();

    JMenuItem item = new JMenuItem("Item Label");
    menu.add(item);

    JButton component = new JButton("button");
    component.addMouseListener(new MouseAdapter() {
      public void mousePressed(MouseEvent evt) {
        if (evt.isPopupTrigger()) {
          menu.show(evt.getComponent(), evt.getX(), evt.getY());
        }
      }

      public void mouseReleased(MouseEvent evt) {
        if (evt.isPopupTrigger()) {
          menu.show(evt.getComponent(), evt.getX(), evt.getY());
        }
      }
    });

  }
}