Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding spacing between elements in JMenuBar

Elements such as File, Edit etc. are too close together when using the JMenuBar in my application, it would look much nicer if there were some space between the elements. Is this possible?

like image 233
Andrei0427 Avatar asked Aug 31 '12 09:08

Andrei0427


5 Answers

Yes, just add MenuBar item with empty text in it and make it not clickable/selectable

like image 179
jdevelop Avatar answered Oct 09 '22 11:10

jdevelop


required to add JComponents that aren't focusable, you can create an space for

  1. JMenuBar

    • JLabel (have to set for required PreferredSize)

    • JSeparator (minimus size is 10pixels, have to setOpaque for JSeparator)

  2. JMenuItem

    • JSeparator (no additional settings required)

    • JLabel (have to set for required PreferredSize)

like image 8
mKorbel Avatar answered Oct 09 '22 09:10

mKorbel


It's old, but I was looking for any solution to the same problem And I came out to this:

You should set margins to yours JMenuItem, like this:

JMenuItem menu = new JMenuItem("My Menu");
menu.setMargin(new Insets(10, 10, 10, 10));
like image 5
Gabriel Câmara Avatar answered Oct 09 '22 11:10

Gabriel Câmara


For a horizontal use you could take a use |.

menu.add(new JMenu("File"));
menu.add(new JMenu("|"));
menu.add(new JMenu("Edit"));

For the vertical use you might simply use a JSeparator or addSeparator():

menu.add(new JMenuItem("Close"));
menu.add(new JSeparator());        // explicit
menu.addSeparator();               // or implicit
menu.add(new JMenuItem("Exit"));

Separator

like image 5
oopbase Avatar answered Oct 09 '22 10:10

oopbase


There is a static method on javax.swing.Box called createHorizontalStrut( int width ) to create an invisible fixed-width component.

The code would look something like this:

JMenuBar menuBar = new JMenuBar();
menuBar.add( new JMenu( "File" ) );
menuBar.add( Box.createHorizontalStrut( 10 ) );  //this will add a 10 pixel space
menuBar.add( new JMenu( "Edit" ) );
like image 1
birkner Avatar answered Oct 09 '22 11:10

birkner