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 requiredPreferredSize
)JSeparator
(minimus size is 10pixels, have tosetOpaque
forJSeparator
)
JMenuItem
JSeparator
(no additional settings required)JLabel
(have to set for requiredPreferredSize
)
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"));
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));
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" ) );
There are two standard ways to add arbitrary spacing to Swing components.
One standard way is to use setMargin to the JMenu objects contained within the JMenuBar object. This is the way Gabriel Câmara suggested above für JMenuItem. This is supposed to work für JMenu objects as well, but I tried it and it did not work.
The second standard way to do this is to add an EmptyBorder to the JMenu objects. This works totally fine. It gives you total control for the exact distances you want to have in all directions.
JMenu jMenuFile = new JMenu("File")
jMenuFile.setBorder(new EmptyBorder(0, 10, 0, 10));
The other answers work well, but can have unexpected spacing due to padding and margins. If you want to have more control of the size of your spacer:
JMenu spacer = new JMenu();
//disable the spacer so that it doesn't behave
//like a menu item
spacer.setEnabled(false);
//Java components are weird. Set all three to
//guarantee that size is used
spacer.setMinimumSize(new Dimension(width, 1));
spacer.setPreferredSize(new Dimension(width, 1));
spacer.setMaximumSize(new Dimension(width, 1));
//add the spacer to your JMenuBar
jMenuBar.add(spacer);
© 2022 - 2024 — McMap. All rights reserved.