javaswingjmenubar

Java JMenuBar is spread over the whole width of the window


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?


Solution

  • 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.