JLabel with multiple lines and alignment to the right

前端 未结 3 512
执笔经年
执笔经年 2020-12-07 02:29

I searched through many posts and figured out that JLabel supports HTML. So I can do

JLabel search  = new JLabel(\"Search
相关标签:
3条回答
  • 2020-12-07 03:09

    Non-breaking spaces ( ) are supported:

    new JLabel("<html>Search<br/>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; By:</html>");
    

    If you want to have real right-alignment, use individual right-aligned labels and combine them:

    JLabel search = new JLabel("Search", SwingConstants.RIGHT);
    JLabel by = new JLabel("By:", SwingConstants.RIGHT);
    
    JPanel combined = new JPanel();
    combined.setOpaque(false);
    combined.setLayout(new GridLayout(2, 1));
    combined.add(search);
    combined.add(by);
    

    or use a read-only JTextPane instead (with \n for line breaks):

    JTextPane text = new JTextPane();
    
    SimpleAttributeSet attributes = new SimpleAttributeSet();
    StyleConstants.setAlignment(attributes, StyleConstants.ALIGN_RIGHT);
    StyleConstants.setFontFamily(attributes, "Default");
    text.setParagraphAttributes(attributes, true);
    text.setEditable(false);
    text.setOpaque(false);
    text.setText("Search\nBy:");
    
    0 讨论(0)
  • 2020-12-07 03:14

    There are a number of ways you might achieve this, one of the safer ways might be to use a <table> and aligning both cells to the right...

    Label wrapped in table

    JLabel label = new JLabel(
                    "<html><table border='0' cellpadding='0' cellspacing='0'>" + 
                                    "<tr><td align='right'>Search</td></tr>" +
                                    "<tr><td align='right'>By:</td></tr></table>"
    );
    

    This overcomes issues with differences between fonts and font rendering on different platforms

    0 讨论(0)
  • 2020-12-07 03:31

    Slightly simpler HTML than seen in @MadProgrammer's answer:

    new JLabel("<html><body style='text-align: right'>Search<br>By:");
    
    0 讨论(0)
提交回复
热议问题