How to add a horizontal gap with a JLabel
Asked Answered
W

4

6

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

I have put an icon and text on it.

<icon><text>

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

<space><icon><text>

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

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

Woolley answered 1/10, 2008 at 10:17 Comment(0)
W
13

I have found the solution!

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

Thanks everyone!

Woolley answered 1/10, 2008 at 10:39 Comment(0)
B
4

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

Bankrupt answered 1/10, 2008 at 10:22 Comment(0)
C
2

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.

Codeine answered 1/10, 2008 at 10:29 Comment(0)
J
1

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

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

Joanniejoao answered 1/10, 2008 at 10:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.