import java.awt.FlowLayout;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
public class B extends MouseAdapter {
JFrame frame = new JFrame();
JPopupMenu popup = new JPopupMenu();
JMenuItem item1 = new JMenuItem("ADD");
JMenuItem item2 = new JMenuItem("DELETE");
public static void main(String arg[]) {
new B();
}
B() {
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setLayout(new FlowLayout());
frame.addMouseListener(this);
popup.add(item1);
popup.add(item2);
frame.add(popup);
frame.setVisible(true);
}
public void mouseClicked(MouseEvent click) {
if(click.isPopupTrigger())
popup.show(frame,click.getX(),click.getY());
}
}
I have written this java code is to display a popup menu with two items on it, but popup menu is not displayed when I right click on frame, please help.
From Java Doc : isPopupTrigger()
Popup menus are triggered differently on different systems. Therefore, isPopupTrigger should be checked in both mousePressed and mouseReleased for proper cross-platform functionality.
Instead of mouseClicked() add below two methods:
public void mousePressed(MouseEvent e) {
if(e.isPopupTrigger())
popup.show(frame,e.getX(),e.getY());
}
public void mouseReleased(MouseEvent e) {
if(e.isPopupTrigger())
popup.show(frame,e.getX(),e.getY());
}
来源:https://stackoverflow.com/questions/28523584/jpopupmenu-is-not-displayed-on-right-click