Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a JMenu have Button behaviour in a JMenuBar

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

        }
like image 353
Kurru Avatar asked Mar 16 '10 17:03

Kurru


2 Answers

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);
like image 54
Nate Avatar answered Sep 22 '22 06:09

Nate


This code sample runs in eclipse, Again concerned about how you are using it?

public class MyMenuFrame extends JFrame {


    public MyMenuFrame() throws HeadlessException {
        super("My Frame");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setSize(400, 300);
        Container pane = this.getContentPane();
        pane.setLayout(new BorderLayout());
        pane.add(new JLabel("Hi there"), BorderLayout.PAGE_START);
        this.setVisible(true);
        JMenuBar menubar = new JMenuBar();
        JMenu menu = new JMenu("File");

        menu.addMenuListener(new MenuListener() {

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

            }

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

            }

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

            }
        });
        menubar.add(menu);
        this.setJMenuBar(menubar );
    }

    public static void main(String[] args) {
        new MyMenuFrame();
    }
}
like image 20
Kannan Ekanath Avatar answered Sep 19 '22 06:09

Kannan Ekanath