将JLabel中的文本右对齐 [英] Align text in JLabel to the right
问题描述
我有一个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 Horizontal对齐
您可以使用 JLabel
构造函数:
JLabel(String text, int horizontalAlignment)
要对齐右边:
JLabel label = new JLabel("Telephone", SwingConstants.RIGHT);
JLabel
还有 setHorizontalAlignment
:
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屋!