菜单上的java动作监听器,而不是菜单项 [英] java action listener on menu, and not on menu item

查看:861
本文介绍了菜单上的java动作监听器,而不是菜单项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要启发。

如何添加动作actionListener事件绑定到菜单,而不是绑定到菜单ITEM
这里是演示代码,这是有效的(在menuITEM上)..

how to add action actionListener event bind to the menu, and not bind to the menu ITEM here is the demo code, that works(on menuITEM)..

menuFileItem.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent e)
                {
                    System.out.println("It works");
                }
            }
        );

但是当我尝试相同时,但只是在菜单本身它不起作用!

but when i try the same , but just on the MENU itself it doesn't work!

menuFile.addActionListener(
            new ActionListener(){
                public void actionPerformed(ActionEvent e)
                {
                    System.out.println("Plz work... :( ");
                }
            }
        );

是否可以将监听器添加到菜单中?我教过的监听器可以添加到所有内容中。

is it possible to add listener to menu? i taught listener could be added to everything.

推荐答案

您可以将 ActionListener 添加到 JMenu ,因为此方法是从 AbstractButton (JMenu文档)

You can add an ActionListener to a JMenu as this method is inherited from AbstractButton. (JMenu Documentation)

JMenu menu = new JMenu("MyMenu");
menu.addActionListener(new ActionListener(){...});

但是,它不是inte nded以这种方式使用: JMenu忽略ActionEvent 。你应该使用 MenuEvent MenuListener

But, it is not intended to be used this way: JMenu ignores ActionEvent. You should use MenuEvent and MenuListener instead.

JMenu menu = new JMenu("MyMenu");
menu.addMenuListener(new MenuListener() {

        @Override
        public void menuSelected(MenuEvent e) {
            System.out.println("menuSelected");

        }

        @Override
        public void menuDeselected(MenuEvent e) {
            System.out.println("menuDeselected");

        }

        @Override
        public void menuCanceled(MenuEvent e) {
            System.out.println("menuCanceled");

        }
    });

这篇关于菜单上的java动作监听器,而不是菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆