java 如何在 Swing 中的组件边框外添加边距?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2883291/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 23:16:44  来源:igfitidea点击:

How do I add a margin outside the border of a component in Swing?

javaswingbordermargin

提问by Jonas

I use multiple components that has a border painted. Is there any easy way to add a margin to the component so that the borders aren't painted so close to eachother?

我使用了多个带有边框的组件。有没有什么简单的方法可以为组件添加边距,以便边框不会彼此靠近?

采纳答案by Alex B

This is typically done using your layout manager. For example, if you are using GridBagLayout, you would set insetson the GridBagConstraintobject to the desired value.

这通常是使用您的布局管理器完成的。例如,如果你正在使用GridBagLayout,您将设置insets在上GridBagConstraint对象为需要的值。

Another option is to use the Boxobject and add a horizontal or vertical struct. See javadocfor Box.createVerticalStrut( int width )and the similar createHorizontalStrut.

另一种选择是使用Box对象并添加水平或垂直结构。请参阅的javadocBox.createVerticalStrut( int width )和类似的createHorizontalStrut

回答by jfpoilpret

Another way to get what you want is to:

获得你想要的东西的另一种方法是:

  1. get the current Borderof your component
  2. if null, set an EmptyBorderfor your component
  3. if not null, create a new CompoundBorder(with an EmptyBorderand the current Borderof the component) and set it for the component
  1. 获取Border组件的电流
  2. 如果nullEmptyBorder为您的组件设置一个
  3. 如果没有null,则创建一个新的 CompoundBorder(带有一个EmptyBorder和当前Border组件的)并为该组件设置它

In code, that should look like that (sorry I haven't tested it):

在代码中,它应该是这样的(抱歉我没有测试过):

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

Where:

在哪里:

  • component is the Swing component to which you want to add a margin
  • top, left, bottom, right are the pixels amounts you want to add around your component
  • component 是要添加边距的 Swing 组件
  • 顶部、左侧、底部、右侧是您要在组件周围添加的像素数量

Note that this method might have an impact (size, alignment) on the form layout, depending on the LayoutManageryou are using. But I think it is worth trying.

请注意,此方法可能会对表单布局产生影响(大小、对齐方式),具体取决于LayoutManager您使用的内容。但我认为值得一试。