JPopupMenu is not displayed on right click

。_饼干妹妹 提交于 2019-12-01 11:34:59

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!