Java JLabel具有多行并向右对齐
我搜索了很多帖子,发现Java JLabel具有多行并向右对齐,java,html,swing,jlabel,Java,Html,Swing,Jlabel,我搜索了很多帖子,发现JLabel支持HTML。 所以我能做到 JLabel search = new JLabel("<html>Search<br/> By:</html>"); 然而,我想要的是 Search By: 在“By:”之前添加空格仅在窗口无法调整大小时有效(而且非常愚蠢)。 有人能告诉我如何修改此代码以使其按我的要求工作吗?支持不间断空格(): new JLabel("<html>Search<br/>
JLabel
支持HTML。
所以我能做到
JLabel search = new JLabel("<html>Search<br/> By:</html>");
然而,我想要的是
Search
By:
在“By:”之前添加空格仅在窗口无法调整大小时有效(而且非常愚蠢)。
有人能告诉我如何修改此代码以使其按我的要求工作吗?支持不间断空格(
):
new JLabel("<html>Search<br/> By:</html>");
或者改用只读的JTextPane
(换行符使用\n
):
有很多方法可以实现这一点,其中一种更安全的方法可能是使用
并将两个单元格向右对齐
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>"
);
JLabel标签=新的JLabel标签(
"" +
“搜索”+
“收件人:”
);
这克服了不同平台上字体和字体呈现之间存在差异的问题与@MadProgrammer的回答相比,HTML稍微简单一些:
new JLabel("<html><body style='text-align: right'>Search<br>By:");
newjlabel(“搜索者:”);
“div”也很有效:新的JLabel(“SearchBy:”);
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:");
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>"
);
new JLabel("<html><body style='text-align: right'>Search<br>By:");