菜单项回调无效

时间:2015-04-10 15:27:17

标签: java swing

//单击"文件"

时,以下回叫功能正常
    menuBar = new JMenuBar();
    frame.setJMenuBar(menuBar);

    mnFile = new JMenu("File");
    mnFile.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            btnNewButton_0.setText("File pressed");
        }
    });
    menuBar.add(mnFile);

//单击菜单项时,回调后无法响应:打开

    mntmOpen = new JMenuItem("Open");
    mntmOpen.addMouseListener(new MouseAdapter() {
        @Override
        public void mouseClicked(MouseEvent e) {
            btnNewButton_0.setText("Open pressed");
        }
    });
    mnFile.add(mntmOpen);

//不确定我缺少什么?

1 个答案:

答案 0 :(得分:2)

不要使用MouseListener !!!

如果您想在点击JMenu时执行某些操作,请使用JPopupMenuListener

JMenu file = new JMenu( "File" );

JPopupMenu popup = file.getPopupMenu();
popup.addPopupMenuListener(new PopupMenuListener()
{
    public void popupMenuCanceled(PopupMenuEvent e) {}

    public void popupMenuWillBecomeInvisible(PopupMenuEvent e) {}

    public void popupMenuWillBecomeVisible(PopupMenuEvent e)
    {
        System.out.println("menu clicked");
    }
});

否则,只需向ActionListener添加JMenuItem,如How to Use Menus上的Swing教程中所示。