HTML wrapped String creates a unwanted new line in

2020-04-19 06:15发布

问题:

When I concentrate a String with a HTML formatted string, and output the String to a JTextPane with a HTMLEditor kit, every appended String wrapped in the HTML tags appears to cause a new line:

// Set the HTML Editor kit for JTExtPAne
    jtextPane.setEditorKit(new HTMLEditorKit());

        String  saveCurrentSentenceState = "Some String";
        String newWord = "new word"; // wrap this in HTML tags

        // Create a HTML String
        String appendHTML = "<html><font color=\"red\">"+newWord+"<</font>";

        // Concatenate with an existing String
        saveCurrentSentenceState += " " + appendHTML;

        jtextPane.setText(appendHTML);

Output in the JTextPane has unwanted line breaks where each HTML String has been concatenated:

Expected output would be all the words in a single line:

hello gello top top hello

This is the string printed to the console:

 hello gello <html><font color="red">top<</font> <html><font color="red">top<</font> hello

I have tried trimming the string but same output:

saveCurrentSentenceState.trim();

As I append the String with a HTML formatted sub string, I do not close the HTML tag, as any concatenated string after a closed HTML tag does not print.

Is there anyway I can stop this newline form printing ?

回答1:

The problem is that you inserts the incorrect HTML (as it was mentioned in the comment of @AndrewThompson). The easiest way in your case to get the correct result is to remove all <html> and </html> tags from your strings, then merge these strings and append <html> and </html> after that. In this case you'll get the correct HTML, that can be processed by the HTMLEditorKit of JTextPane