如何在JLabel中添加水平间距

6
我有一个JLabel(实际上是一个JXLabel)。
我在它上面放了一个图标和文本。
现在我想在组件左侧添加一些间距,就像这样:
4个回答

13

我已经找到解决方案了!

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

谢谢大家!


4
这样做法:并不是很清晰,但你可以通过在标签上添加一定宽度的透明边框来增加间距。

2
如果您想将标签推到其容器的一侧,可以添加粘合剂。类似于这样的代码:
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());

尽管您的问题不是很清楚。

1

无需修改JLabel的preferredSize,您可以使用GridBagLayout管理器来指定组件之间的间距,只需在容器中使用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);

请注意,在设置约束条件时,我省略了许多配置属性,您最好阅读GridBagLayout的文档。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接