Search code examples
javaswingjlabelright-align

How do I right align text within a JLabel?


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.


Solution

  • The setPreferredSize/MinimumSize/MaximumSize methods is dependent from the layout manager of the parent component (in this case panel).

    First try with setMaximumSize instead of setPreferredSize, if I'm not going wrong should work with BoxLayout.

    In addition: probably you have to use and play around with glues:

    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    panel.add(Box.createHorizontalGlue());
    panel.add(label);
    panel.add(Box.createHorizontalGlue());
    

    If you need the Y_AXIS BoxLayout you could also used nested panel:

    verticalPanel.setLayout(new BoxLayout(verticalPanel, BoxLayout.Y_AXIS));    
    panel.setLayout(new BoxLayout(panel, BoxLayout.X_AXIS));
    panel.add(Box.createHorizontalGlue());
    panel.add(label);
    panel.add(Box.createHorizontalGlue());
    verticalPanel.add(panel);