Java JMenuBar is spread over the whole width of the window

423 Views Asked by At

I want to create a very simple JMenuBar with 2 clickable JMenuItems with the following code:

JFrame window = new JFrame();
JMenuBar bar = new JMenuBar();
JMenuItem open = new JMenuItem("Open"), reload = new JMenuItem("Reload");
bar.add(open);
bar.add(reload);
window.setJMenuBar(bar);
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.pack();
window.setVisible(true);

However, the two Items have a huge space in between them and I have no idea where this is coming from: enter image description here

I would expect the "Reload" item to be right next to the "Open" item.
This is the very first part of the code that runs (with a breakpoint immediately after), so nothing else can interfere with it.
Is there something 'obvious' I am missing?

2

There are 2 best solutions below

1
camickr On BEST ANSWER

The point is that I don't want to create Menus,

Well, a menu is designed to be clicked on and then display a popup with menu items.

If you want the ability to click on a button directly, then use a JToolBar. Read the section from the Swing tutorial on How to use Toolbars for more information and working examples.

1
CcmU On

You're probably getting confused between JMenu and JMenuItem. I suggest you to check this tutorial of the docs, it'll help to comprehend the differences between the various objects.

To do what I understood you want to do you should use something like:


    JFrame window = new JFrame();
    JMenuBar bar = new JMenuBar();
    JMenu open = new JMenu("Open"), reload = new JMenu("Reload");
    
    bar.add(open);
    bar.add(reload);
    ...

If i shattered and you meant to create a single JMenu with two JMenuItems you can easily do the following:


    JFrame window = new JFrame();
    JMenuBar bar = new JMenuBar();
    JMenu menu = new JMenu("A menu");    // creating a menu to hold the two items
    JMenuItem open = new JMenuItem("Open"), reload = new JMenuItem("Reload");
    
    menu.add(open);
    menu.add(reload);
    ...