How do I right align text within a JLabel?

Grammin picture Grammin · Jun 6, 2011 · Viewed 24.2k times · Source

I have the following code:

JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

for(int xx =0; xx < 3; xx++)
{
    JLabel label = new JLabel("String");
    label.setPreferredSize(new Dimension(300,15));
    label.setHorizontalAlignment(JLabel.RIGHT);

    panel.add(label);
}

This is how I would like the text to look:

[                         String]
[                         String]
[                         String]

this is how it looks

[String]
[String]
[String]

For some reason label doesn't get set to the preferred size I specified and I think because of this it doesn't right align my label text. But im not sure. Any help would be appreciated.

Answer

dalvarezmartinez1 picture dalvarezmartinez1 · Feb 27, 2013
JLabel label = new JLabel("String", SwingConstants.RIGHT);

:)