JLabel with multiple lines and alignment to the right

前端 未结 3 522
执笔经年
执笔经年 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("Search
           By:");

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

提交回复
热议问题