Align text in JLabel to the right

2022-08-31 19:49:33

I have a JPanel with some JLabel added with the method of JPanel. I want to align the JLabel to the right like the image below but I don't know how to do that. Any Idea? Thanks!add()

enter image description here


答案 1

This can be done in two ways.

JLabel Horizontal Alignment

You can use the constructor:JLabel

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);

答案 2
JLabel label = new JLabel("fax", SwingConstants.RIGHT);

推荐