1

单击 JMenu(或单击相邻的 JMenu 然后将鼠标拖到其上)时的默认行为是展开并显示其子菜单和菜单项。当这种情况(展开菜单时)发生时,我可以关联其他行为(例如生成事件)吗?

4

2 回答 2

3

您可以使用MenuListenerwhich 应该为您提供有关菜单状态的信息。

这个简单的示例在每次打开菜单时创建一个新菜单项...

import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.MenuEvent;
import javax.swing.event.MenuListener;

public class TestMenuBar {

    public static void main(String[] args) {
        new TestMenuBar();
    }

    public TestMenuBar() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }

                JMenuBar mb = new JMenuBar();
                JMenu main = new JMenu("Test");
                mb.add(main);

                main.addMenuListener(new MenuListener() {
                    @Override
                    public void menuSelected(MenuEvent e) {
                        System.out.println("Selected");
                        JMenu menu = (JMenu) e.getSource();

                        menu.add(new JMenuItem("I'm dynamiclly created"));
                    }

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

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

                JFrame frame = new JFrame("Testing");
                frame.setJMenuBar(mb);
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.setSize(200, 200);
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }        
}
于 2013-07-01T00:19:49.783 回答
3

有专门针对 JMenus 的事件监听器类:

javax.swing.event.MenuListener

javax.swing.event.MenuDragMouseListener

您需要调用以将这些与组件相关联的方法是

JMenuComponentName.addMenuListener(MenuListener m);JMenuComponentName.addMenuMouseDragListener(MenuDragMouseListener m);,分别。

于 2013-07-01T00:21:33.323 回答