将JLabel中的文本右对齐 [英] Align text in JLabel to the right

查看:353
本文介绍了将JLabel中的文本右对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JPanel,其中一些JLabel添加了JPanel的 add()方法。我想将JLabel对齐到右边,如下图所示,但我不知道该怎么做。任何的想法?谢谢!

I have a JPanel with some JLabel added with the add() 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!

推荐答案

这可以通过两种方式完成。

This can be done in two ways.

JLabel Horizo​​ntal对齐

您可以使用 JLabel 构造函数

JLabel(String text, int horizontalAlignment) 

要对齐右边:

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

JLabel 还有 setHorizo​​ntalAlignment

label.setHorizontalAlignment(SwingConstants.RIGHT);

这假设组件占用了容器中的整个宽度。

This assumes the component takes up the whole width in the container.

使用布局

另一种方法是使用布局将组件实际对齐到右边,同时确保他们没有占据整个宽度。以下是 BoxLayout 的示例:

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中的文本右对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆