Search code examples
javaswingjmenuitemjmenubar

How do I place two JMenuItems adjacent to each other?


My Code:

JMenuBar bar = new JMenuBar();
JMenu menu = new JMenu("Edit circle");
JMenuItem help = new JMenuItem("Help");
JMenuItem exit = new JMenuItem("Exit");

bar.add(menu);
bar.add(help);
bar.add(exit);

Output of the JMenuBar:

OUTPUT

I want the output to be something like this:

EXPECTED_OUTPUT

What do I need to do in order to get the expected output?


Solution

  • you cannot add JMenuItem in JMenuBar. so try this.. it'll work..

        JMenuBar bar = new JMenuBar();
        JMenu menu1 = new JMenu("Edit circle");
        JMenu help = new JMenu("Help");
        JMenu exit = new JMenu("Exit");
        bar.add(menu1);
        bar.add(help);
        bar.add(exit);
        exit.addMenuListener(new MenuListener() {
    
            @Override
            public void menuSelected(MenuEvent e) {
                System.out.println("Exiting");
            }
    
            @Override
            public void menuDeselected(MenuEvent e) {
            }
    
            @Override
            public void menuCanceled(MenuEvent e) {
            }
        });
    

    you cannot add ActionListener to JMenu. use MenuListener..

    reference from this...