Search code examples
javaswingalignmentjlabelimageicon

Align text and icon differently in JLabel


i'm trying to create a JLabel that has text aligned left and icon aligned right, i tried this code:

_ip = new JLabel(ip);
_ip.setFont(boldFont);
_ip.setBounds(5, 0, 100, 50);
_ip.setIcon(images.ipBan);
_ip.setBorder(BorderFactory.createLineBorder(Color.black, 1));
_ip.setHorizontalTextPosition(SwingConstants.LEFT);
add(_ip);

And this is what i get:

Alignment preview

The red image shows the actual image alignment, the gray one shows where i want my image to be.

If i add

_ip.setAlignmentX(JLabel.RIGHT_ALIGNMENT);

Nothing happens, and if i add

_ip.setHorizontalAlignment(JLabel.RIGHT);

Icon is aligned right, but also text is aligned right, and i want it to align left

Is there a way to do it?


Solution

  • Alternatively, you can use a JPanel with a suitable layout, as shown here.

    image