简体   繁体   English

将 JLabel 中的文本向右对齐

[英]Align text in JLabel to the right

I have a JPanel with some JLabel added with the add() method of JPanel.我有一个 JPanel,其中使用 JPanel 的add()方法add()了一些 JLabel。 I want to align the JLabel to the right like the image below but I don't know how to do that.我想像下图一样将 JLabel 向右对齐,但我不知道该怎么做。 Any Idea?任何的想法? Thanks!谢谢!

在此处输入图片说明

This can be done in two ways.这可以通过两种方式完成。

JLabel Horizontal Alignment JLabel 水平对齐

You can use the JLabel constructor :您可以使用JLabel 构造函数

JLabel(String text, int horizontalAlignment) 

To align to the right:要向右对齐:

JLabel label = new JLabel("Telephone", SwingConstants.RIGHT);

JLabel also has setHorizontalAlignment : JLabel也有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 :这是一个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);

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.但是,我相信您想让标签在 1 行中只有 2 个单词。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM