java 如何使用 JLabel 添加水平间隙

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/156975/
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 11:13:54  来源:igfitidea点击:

How to add a horizontal gap with a JLabel

javaswingjlabelswingx

提问by michelemarcon

I have a JLabel (actually, it is a JXLabel).

我有一个 JLabel(实际上,它是一个 JXLabel)。

I have put an icon and text on it.

我在上面放了一个图标和文字。

<icon><text>

<icon><text>

Now I wand to add some spacing on the left side of the component, like this:

现在我想在组件的左侧添加一些间距,如下所示:

<space><icon><text>

<space><icon><text>

I DON'T accept suggestion to move the JLabel or add spacing by modifying the image.

我不接受通过修改图像来移动 JLabel 或添加间距的建议。

I just want to know how to do it with plain java code.

我只想知道如何使用纯 Java 代码来实现。

回答by michelemarcon

I have found the solution!

我找到了解决方案!

setBorder(new EmptyBorder(0,10,0,0));

Thanks everyone!

感谢大家!

回答by Jasper

The like this: is not very clear, but you can add spacing by adding a transparent border of a certain width to the label

像这样:不是很清楚,但是可以通过给label添加一定宽度的透明边框来增加间距

回答by rjohnston

If you're trying to push the label to one side of it's container, you can add a glue. Something like this:

如果您试图将标签推到容器的一侧,您可以添加胶水。像这样的东西:

JPanel panel = new JPanel();
panel.setLayoutManager(new BoxLayout(panel, BoxLayout.LINE_AXIS);

panel.add(new JLabel("this is your label with it's image and text"));

panel.add(Box.createHorizontalGlue());

Though your question isn't very clear.

虽然你的问题不是很清楚。

回答by Telcontar

You dont need to modify the preferredSize of the JLabel, you can use the GridBagLayoutManager to specify separations between components, you only have to use the GridBagLayout in the container and add the JXLabel to it with a GridBagConstraintsobject specifiying the insets to the left:

您不需要修改 JLabel 的 preferredSize,您可以使用GridBagLayoutManager 来指定组件之间的分隔,您只需要在容器中使用 GridBagLayout 并使用GridBagConstraints对象向其添加 JXLabel 并指定左侧的插图:

JPanel panel=new JPanel(new GridBagLayout());
JLabel label=new JLabel("xxxxx");

GridBagConstraints constraints=new GridBagConstraints();

constraints.insest.left=X; // X= number of pixels of separation from the left component

panel.add(label,constraints);

Note that i have omitted a lot of configuration properties in the setup of the constraints, you better read the documentacion of GridBagLayout

请注意,我在约束的设置中省略了很多配置属性,您最好阅读GridBagLayout的文档