简体   繁体   中英

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

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

Quick solution is to avoid writing </html> at the end of the text. Swing needs only the opening tag <html> in order to show HTML text. 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:

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.

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. 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):

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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