Align text in JLabel to the right
To me, it seems as if your actual intention is to put different words on different lines. But let me answer your first question:
JLabel lab=new JLabel("text");
lab.setHorizontalAlignment(SwingConstants.LEFT);
And if you have an image:
JLabel lab=new Jlabel("text");
lab.setIcon(new ImageIcon("path//img.png"));
lab.setHorizontalTextPosition(SwingConstants.LEFT);
But, I believe you want to make the label such that there are only 2 words on 1 line.
In that case try this:
String urText="<html>You can<br>use basic HTML<br>in Swing<br> components,"
+"Hope<br> I helped!";
JLabel lac=new JLabel(urText);
lac.setAlignmentX(Component.RIGHT_ALIGNMENT);
This can be done in two ways.
JLabel Horizontal Alignment
You can use the JLabel
constructor:
JLabel(String text, int horizontalAlignment)
To align to the right:
JLabel label = new JLabel("Telephone", SwingConstants.RIGHT);
JLabel
also has setHorizontalAlignment
:
label.setHorizontalAlignment(SwingConstants.RIGHT);
This assumes the component takes up the whole width in the container.
Using Layout
A different approach is to use the layout to actually align the component to the right, whilst ensuring they do not take the whole width. Here is an example with BoxLayout
:
Box box = Box.createVerticalBox();
JLabel label1 = new JLabel("test1, the beginning");
label1.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label1);
JLabel label2 = new JLabel("test2, some more");
label2.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label2);
JLabel label3 = new JLabel("test3");
label3.setAlignmentX(Component.RIGHT_ALIGNMENT);
box.add(label3);
add(box);
JLabel label = new JLabel("fax", SwingConstants.RIGHT);