具有多行并向右对齐的 JLabel

JLabel with multiple lines and alignment to the right

我搜索了很多帖子,发现 JLabel 支持 HTML。 所以我可以做

JLabel search  = new JLabel("<html>Search<br/> By:</html>");

获取多行。上面的代码将导致

Search  
By:  

不过,我想要的是

Search  
   By: 

在 "By:" 之前添加空格只有在 window 不可调整大小时才有效(非常愚蠢,哈哈)。 谁能告诉我如何修改此代码以使其按我的意愿工作?

支持不间断空格 (&nbsp;):

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

如果您想要真正的右对齐,请使用单独的右对齐标签并将它们组合起来:

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

或使用只读 JTextPane 代替(使用 \n 换行):

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

有多种方法可以实现此目的,其中一种更安全的方法可能是使用 <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>"
);

这解决了不同平台上字体和字体呈现差异的问题

比@MadProgrammer 的回答稍微简单HTML:

new JLabel("<html><body style='text-align: right'>Search<br>By:");