10

I want to align my JLabel to the left.

    String lText = "<html><b><font color = white face = comic sans ms size = 20>mybook</font></b></html>";
    JLabel label = new JLabel(lText);
    label.setBorder(new EmptyBorder(25,0,25,500));

I tried to do it using EmptyBorder but it isnt aligning properly. I am using FlowLayout

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Archit Verma
  • 1,911
  • 5
  • 28
  • 46

2 Answers2

15

FlowLayout uses CENTER alignment by default. Try using LEFT alignment for your JLabel JPanel container

myJPanel.setLayout(new FlowLayout(FlowLayout.LEFT));
Reimeus
  • 158,255
  • 15
  • 216
  • 276
  • 2
    This align the whole panel to the left. I just want to align my label on the left. – Archit Verma Jul 07 '13 at 11:12
  • @ArchitVerma : `Put the JLabel` on a `JPanel` with as suggested in the answer, and keep this new `JPanel` in place of the present position of your `JLabel` :-) Won't that do ? – nIcE cOw Jul 07 '13 at 11:14
  • I.e. you will need to use nested containers using if using `FlowLayout` – Reimeus Jul 07 '13 at 11:16
4

You might wish to set the JLabel's horizontalAlignment property. One way is via its constructor. Try:

JLabel label = new JLabel(lText, SwingConstants.LEFT);

This can also be done via the expected setter method:

label.setHorizontalAlignment(SwingConstants.LEFT);
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • 4
    This will only align the text inside the border of the label, not how the label is aligned in the panel. – Günter Sep 08 '14 at 05:50