Right click to trigger the popup menu : Mouse Event « Swing Event « Java Tutorial






import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public class Test extends JFrame {
  JPopupMenu menu = new JPopupMenu("Popup");

  class MyLabel extends JLabel {
    public MyLabel(String text) {
      super(text);
      addMouseListener(new PopupTriggerListener());
    }

    class PopupTriggerListener extends MouseAdapter {
      public void mousePressed(MouseEvent ev) {
        if (ev.isPopupTrigger()) {
          menu.show(ev.getComponent(), ev.getX(), ev.getY());
        }
      }

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

      public void mouseClicked(MouseEvent ev) {
      }
    }
  }

  JLabel label = new MyLabel("right-click");

  public Test() {
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JMenuItem item = new JMenuItem("Test1");
    item.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Menu item Test1");
      }
    });
    menu.add(item);

    item = new JMenuItem("Test2");
    item.addActionListener(new ActionListener() {
      public void actionPerformed(ActionEvent e) {
        System.out.println("Menu item Test2");
      }
    });
    menu.add(item);

    getContentPane().add(label);
    pack();
    setSize(300, 100);
  }

  public static void main(String[] args) {
    new Test().setVisible(true);
  }
}








15.28.Mouse Event
15.28.1.Mouse event popup menu triggered
15.28.2.Right click to trigger the popup menu
15.28.3.Using SwingUtilities for Mouse Button IdentificationUsing SwingUtilities for Mouse Button Identification
15.28.4.Uses a subclass of MouseInputAdapter to listen to mouse events and mouse-motion eventsUses a subclass of MouseInputAdapter to listen to mouse events and mouse-motion events
15.28.5.Handling Mouse Clicks
15.28.6.InputEvent.BUTTON1_MASK (for left mouse button)
15.28.7.InputEvent.BUTTON2_MASK (for middle mouse button)
15.28.8.InputEvent.BUTTON3_MASK (for right mouse button)
15.28.9.Detecting Double and Triple Clicks