Add the specified pop-up menu the specified component. - Java Swing

Java examples for Swing:JPopupMenu

Description

Add the specified pop-up menu the specified component.

Demo Code

/*/*from   ww w. j ava  2 s.c  o m*/
 * Copyright (c) 2011, 2020, Frank Jiang and/or its affiliates. All rights
 * reserved. SwingUtils.java is built in 2012-11-2.
 */
//package com.java2s;
import java.awt.Component;

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

import javax.swing.JPopupMenu;

public class Main {
    /**
     * Add the specified pop-up menu the specified component.
     * 
     * @param component
     *            the specified component
     * @param popup
     *            the specified pop-up menu
     */
    public static void addPopup(Component component, final JPopupMenu popup) {
        component.addMouseListener(new MouseAdapter() {
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger())
                    showMenu(e);
            }

            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger())
                    showMenu(e);
            }

            private void showMenu(MouseEvent e) {
                popup.show(e.getComponent(), e.getX(), e.getY());
            }
        });
    }
}

Related Tutorials