2012-08-31 87 views
6

当在我的应用程序中使用JMenuBar时,元素(如文件,编辑等)太靠近了,如果元素之间有一些空间,看起来会更好。这可能吗?在JMenuBar中添加元素之间的间距

+1

如果您使用的是NetBeans尝试右键单击组件,并单击周围组件,如果你需要空间 –

+1

空间,然后尝试menubar.add(新JPanel( ));它为我工作。 –

回答

6

是的,就在它空的文本添加菜单栏项目,并使其不可点击/可选择

+2

谢谢你,这工作得很好PS。 .setClickable()和.setSelectable()不存在,而是对遇到同样问题的人使用.setEnabled() – Andrei0427

5

对于横向使用,你可以采取使用|

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

对于垂直使用您可以简单地使用JSeparatoraddSeparator()

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

Separator

7

添加JComponents要求不focusable,您可以创建一个空间

  1. JMenuBar

    • JLabel(必须为所需PreferredSize设置)

    • JSeparator(微小按蚊大小是10pixels,必须setOpaqueJSeparator

  2. JMenuItem

    (无需额外的设置)
    • JSeparator

    • JLabel(必须为需要PreferredSize设置)

2

这是老了,但我一直在寻找任何解决同样的问题 我出来这个:

你应该为你的JMenuItem设置边距,就像t他的:

JMenuItem menu = new JMenuItem("My Menu"); 
menu.setMargin(new Insets(10, 10, 10, 10)); 
1

在javax.swing.Box上有一个名为createHorizo​​ntalStrut(int width)的静态方法来创建不可见的固定宽度组件。

的代码会是这个样子:

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")); 
0

其他的答案很好地工作,但可以有意想不到的间距由于填充和利润。如果您希望您的间隔体的尺寸进行更多的控制:

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