Trigger a JPopupMenu with mouse event in Java

Description

The following code shows how to trigger a JPopupMenu with mouse event.

Example


//from   www.  jav a  2s .  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");
//  item.addActionListener(actionListener);
    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());
        }
      }
    });

  }
}

The code above generates the following result.

Trigger a JPopupMenu with mouse event in Java




















Home »
  Java Tutorial »
    Swing »




Action
Border
Color Chooser
Drag and Drop
Event
Font Chooser
JButton
JCheckBox
JComboBox
JDialog
JEditorPane
JFileChooser
JFormattedText
JFrame
JLabel
JList
JOptionPane
JPasswordField
JProgressBar
JRadioButton
JScrollBar
JScrollPane
JSeparator
JSlider
JSpinner
JSplitPane
JTabbedPane
JTable
JTextArea
JTextField
JTextPane
JToggleButton
JToolTip
JTree
Layout
Menu
Timer