简体   繁体   English

如何在 Java Swing 中将 html 文本附加到 JLabel

[英]How to append html text to JLabel in Java Swing

I'm trying to append text with HTML tags to text that is already in a JLabel and also has HTML tags我正在尝试将带有 HTML 标签的文本附加到 JLabel 中已有的文本并且也有 HTML 标签

public class BattleConsoleUI {
    private JLabel battleInfo = new JLabel("<html> Hello World <br></html>");

battleInfo.setText(battleInfo.getText() + 
            "<html> HERO NAME :   " +
            "<br> HERO CLASS      :   "  +
            "<br> HERO LEVEL      :   "  +
            "<br> XP              :   "  +
            "<br> ATTACK POINTS   :   "  +
            "<br> DEFENCE POINTS  :   "  +
            "<br> HIT POINTS      :   "  + 
            "</html>");
}

I'm expecting it to display Hello World plus the appended text but the rest of the text is not displayed because of the first closing HTML tag我希望它显示 Hello World 加上附加的文本,但由于第一个关闭的 HTML 标记,其余文本未显示

Quick solution is to avoid writing </html> at the end of the text.快速解决方案是避免在文本末尾写入</html> Swing needs only the opening tag <html> in order to show HTML text. Swing 只需要开始标记<html>即可显示 HTML 文本。 Something like:就像是:

label.setText("<html>first text");
label.setText(label.getText() + " this is second"); //Still an HTML text

If you insist of closing the HTML tag and using </html> at the end, you will have to replace it before appending the new text:如果您坚持关闭 HTML 标记并在最后使用</html> ,则必须在附加新文本之前替换它:

label.setText(label.getText().replaceAll("</html>","") + "i append a text</html>");

Of course instead of replaceAll you could use substring and other things, but this is what i would use.当然,您可以使用substring和其他东西代替replaceAll ,但这是我会使用的。

You are making the variable itself to be first set and then again inside that get text.您首先要设置变量本身,然后在获取文本中再次设置。 You can do simple thing is that make two different string variable and set them to jlabel.您可以做的简单的事情是创建两个不同的字符串变量并将它们设置为 jlabel。 As per here you can :按照这里你可以:


String htmlstr1 = "html hello world tag";

String htmlstr2 = "<html> HERO NAME :   "
    +
                "<br> HERO CLASS      :   "  +
                "<br> HERO LEVEL      :   "  +
                "<br> XP              :   "  +
                "<br> ATTACK POINTS   :   "  +
                "<br> DEFENCE POINTS  :   "  +
                "<br> HIT POINTS      :   "  + "</html>");
Jlabel.setText(htmlstr1+htmlstr2):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM