Adding a JMenu to a JPanel

paranoia25 picture paranoia25 · Feb 8, 2013 · Viewed 11k times · Source

I need to have a JMenu (the one with the arrow on right which can display JMenuItem) in a JPanel. The problem is that when I do that the JMenu is not activate on mouse rollover... I don't know how to do that and if it's possible.

Answer

Guillaume Polet picture Guillaume Polet · Feb 8, 2013

If you wrap your JMenu in a JMenuBar, it works as expected.

Here is a demo example:

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.SwingUtilities;

public class TestMenus {

    private JMenuBar createMenuBar(String name, int depth) {
        JMenuBar bar = new JMenuBar();
        bar.add(createMenu(name, depth));
        return bar;
    }

    private JMenu createMenu(String name, int depth) {
        JMenu menu = new JMenu(name);
        for (int i = 0; i < 5; i++) {
            if (depth > 0) {
                menu.add(createMenu("sub-" + name, depth - 1));
            }
        }
        for (int i = 0; i < 5; i++) {
            menu.add(createMenuItem("Menu item " + (i + 1)));
        }
        return menu;
    }

    private JMenuItem createMenuItem(String name) {
        final JMenuItem jMenuItem = new JMenuItem(name);
        jMenuItem.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(jMenuItem, "Successfully pressed a menu item");
            }
        });
        return jMenuItem;
    }

    protected void initUI() {
        JFrame frame = new JFrame(TestMenus.class.getSimpleName());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(createMenuBar("Root menu", 3));
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {

            @Override
            public void run() {
                new TestMenus().initUI();
            }
        });
    }

}

An the result:

Result of menus added to a JFrame content pane