How to make a JMenu have Button behaviour in a JMenuBar

Kurru picture Kurru · Mar 16, 2010 · Viewed 24k times · Source

I was trying to make a JMenu behave like a JButton but I'm having some problems and hopefully someone here can help!

I've added a MenuListener to the JMenu item with this but I cant get the popup menu/focus to leave to enable me to properly click the JMenu repeated times to trigger this function and i was hoping someone could tell me what i'm doing wrong. Thanks.

public void menuSelected(MenuEvent e)
        {
            ... // do stuff here code
            JMenu source = (JMenu)e.getSource();
            source.setSelected(false);
            source.setPopupMenuVisible(false);

        }

Answer

Nate picture Nate · Mar 16, 2010

Not completely sure what you're asking...

But JMenuBar inherits from Container - if you'd rather add a JButton to it than a JMenu you can simply call -

JMenuBar menuBar = ....
JButton myButton = ....
menuBar.add(myButton);