Adding distance between elements in JMenuBar

Elements like File, Edit, etc. too close to each other when using JMenuBar in my application, it would look much nicer if there was some space between the elements. Is it possible?

+6
source share
7 answers

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

+6
source

required to add JComponents that are not focusable , you can create a space for

  • JMenuBar

    • JLabel (must be installed for the required PreferredSize )

    • JSeparator (minimum size - 10 pixels, for JSeparator - setOpaque )

  • JMenuItem

    • JSeparator (no additional settings required)

    • JLabel (must be installed for the required PreferredSize )

+7
source

For horizontal use you can use | .

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

For vertical use, you can simply use JSeparator or addSeparator() :

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

Separator

+5
source

This is old, but I was looking for any solution to the same problem And I came to this:

You must set the fields for your JMenuItem, for example:

 JMenuItem menu = new JMenuItem("My Menu"); menu.setMargin(new Insets(10, 10, 10, 10)); 
+3
source

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

The code looks 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" ) ); 
+1
source

Other answers work well, but may have an unexpected interval due to padding and fields. If you want more control over 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); 
0
source

There are two standard ways to add custom spacing to Swing components.

One standard way is to use setMargin for JMenu objects contained in a JMenuBar object. This is the method suggested by Gabriel Camara above for JMenuItem. It is also supposed to work with JMenu objects, but I tried, and it didn't work.

The second standard way to do this is to add an EmptyBorder to JMenu objects. This works perfectly fine and gives you full control over the exact distances you want in all directions.

 JMenu jMenuFile = new JMenu("File") jMenuFile.setBorder(new EmptyBorder(0, 10, 0, 10)); 
0
source

Source: https://habr.com/ru/post/924256/


All Articles