设置JMenu Margin不起作用

时间:2014-02-20 09:32:05

标签: java swing jmenu jmenubar preferredsize

我正在创建一个带有JMenu的JMenuBar,并在每个JMenu中设置边距。但是给定的保证金在每个JMenu中都不起作用。如何正确设置JMenuMargin?

 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();
             }
         });
     }
 }

1 个答案:

答案 0 :(得分:5)

要设置保证金,您可以尝试在JMenu中使用html代码,例如:

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

enter image description here

您也可以将EmptyBorder添加到JMenu

file.setBorder(BorderFactory.createCompoundBorder(file.getBorder(),BorderFactory.createEmptyBorder(0, 0, 20, 0)));