Question

I'm creating a JMenuBar with some JMenu and set margin in each JMenu. But the given margin not working in each JMenu. How to setMargin of JMenu correctly?

 import javax.swing.*;

 public class JMenuDemo extends JFrame {

     private JMenuBar bar;

     public JMenuDemo() {
         super("Menu example");
         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
         setVisible(true);

         initialize();
     }

     private void initialize() {
         bar = new JMenuBar();
         int menuHeight = 40;

         JMenu file = new JMenu("File");
         file.setPreferredSize(new java.awt.Dimension(50, menuHeight));
         file.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
         file.setMargin(new java.awt.Insets(0, 0, 20, 0));

         JMenuItem newItem = new JMenuItem("New");
         file.add(newItem);
         JMenuItem openItem = new JMenuItem("Open");
         file.add(openItem);
         bar.add(file);

         JMenu test = new JMenu("Test");
         test.setPreferredSize(new java.awt.Dimension(60, menuHeight));
         test.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
         test.setMargin(new java.awt.Insets(0, 0, 20, 0));
         bar.add(test);

         setJMenuBar(bar);

         getContentPane();
         setSize(400, 200);
     }

     public static void main(String[] args) {
         UIManager.getCrossPlatformLookAndFeelClassName(); 

         java.awt.EventQueue.invokeLater(new Runnable() {
             @Override
             public void run() {
                 new JMenuDemo();
             }
         });
     }
 }
Was it helpful?

Solution

For setting margin you can try to use html code inside your JMenu, for example :

JMenu file = new JMenu("<html><p style='margin-bottom:20'>File");

enter image description here

Also you can add EmptyBorder to your JMenu :

file.setBorder(BorderFactory.createCompoundBorder(file.getBorder(),BorderFactory.createEmptyBorder(0, 0, 20, 0)));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top