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?
Yes, just add MenuBar item with empty text in it and make it not clickable/selectable
required to add JComponents
that aren't focusable
, you can create an space for
JMenuBar
JLabel
(have to set for required PreferredSize
)
JSeparator
(minimus size is 10pixels, have to setOpaque
for JSeparator
)
JMenuItem
JSeparator
(no additional settings required)
JLabel
(have to set for required PreferredSize
)
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));
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"));
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" ) );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With