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.
Home »
Java Tutorial »
Swing »
Java Tutorial »
Swing »