如何让JMenu在展开时做点什么?

时间:2013-07-01 00:01:37

标签: java swing events listener jmenu

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

2 个答案:

答案 0 :(得分:3)

您可以使用MenuListener,它可以为您提供有关菜单状态的信息。

这个简单的例子每次打开菜单时都会创建一个新的菜单项...

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);
            }
        });
    }        
}

答案 1 :(得分:3)

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

javax.swing.event.MenuListener

javax.swing.event.MenuDragMouseListener

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

分别为

JMenuComponentName.addMenuListener(MenuListener m);JMenuComponentName.addMenuMouseDragListener(MenuDragMouseListener m);