如何在Swing中的组件边框外添加边距?
我使用了多个绘有边框的组件。 有没有简单的方法为组件添加边距,以便边框不会彼此如此接近?
这通常使用您的布局管理器完成。 例如,如果您使用的是GridBagLayout
,则可以将GridBagConstraint
对象上的insets
设置为所需的值。
另一种选择是使用Box
对象并添加水平或垂直结构。 请参阅Box.createVerticalStrut( int width )
javadoc和类似的createHorizontalStrut
。
得到你想要的另一种方法是:
- 获取组件的当前
Border
- 如果为
null
,EmptyBorder
组件设置EmptyBorder
- 如果不为
null
,则创建一个新的CompoundBorder
(具有EmptyBorder
和组件的当前Border
)并为组件设置它
在代码中,应该看起来像那样(抱歉,我还没有测试过):
Border current = component.getBorder(); Border empty = new EmptyBorder(top, left, bottom right); if (current == null) { component.setBorder(empty); } else { component.setBorder(new CompoundBorder(empty, current)); }
哪里:
- component是要添加边距的Swing组件
- top,left,bottom,right是要在组件周围添加的像素数量
请注意,此方法可能会对表单布局产生影响(大小,对齐),具体取决于您使用的LayoutManager
。 但我认为值得尝试。