如何确保右键单击时JMenu不关闭?

时间:2019-11-17 16:06:48

标签: java popup mouselistener jmenu jmenuitem

我正在尝试在菜单项上添加带有右键单击功能的功能,但是通过单击鼠标左键和右键来关闭菜单。如何停止关闭?

顺便说一句,我得到了错误:

线程“ AWT-EventQueue-0”中的异常java.awt.IllegalComponentStateException:必须在屏幕上显示组件才能确定其位置

所以我可以肯定这是因为右键单击菜单会关闭

JMenuItem item = new JMenuItem(filename);
item.addMouseListener(new MouseAdapter() {
    public void mousePressed(MouseEvent e) {
        try {
            if(e.getButton() == MouseEvent.BUTTON1){

                ChartConfiguration.openChartConfiguration(fileEntry.getAbsolutePath(), DataAnalyzer.this, 
                chartManager);
            }else if(e.getButton() == MouseEvent.BUTTON2){
                showPopUp(e);
            }
        } catch (FileNotFoundException fnfe) {
            Toast.makeToast(DataAnalyzer.this, "Error Loading File", Toast.DURATION_MEDIUM);
        } catch (IOException ex) {
            Toast.makeToast(DataAnalyzer.this, "Error Loading File", Toast.DURATION_MEDIUM);
        }
    }

    private void showPopUp(MouseEvent e) {
        PopUpMenu menu = new PopUpMenu();
        menu.show(e.getComponent(), e.getX(), e.getY());
    }

    class PopUpMenu extends JPopupMenu {
        JMenuItem deleteItem;
        public PopUpMenu() {
            deleteItem = new JMenuItem("Delete");
            add(deleteItem);
        }
    }
});

0 个答案:

没有答案