Align text in JLabel to the right

后端 未结 3 2172
太阳男子
太阳男子 2020-12-14 05:50

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

相关标签:
3条回答
  • 2020-12-14 06:10
    JLabel label = new JLabel("fax", SwingConstants.RIGHT);
    
    0 讨论(0)
  • 2020-12-14 06:11

    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);
    
    0 讨论(0)
  • 2020-12-14 06:21

    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);
    
    0 讨论(0)
提交回复
热议问题