Search code examples
javahtmlswingjeditorpane

Cant add text to JEditorPane with text/html


I have a JEditorPane in my class and am trying to add text to it. (I didn't use a text area or pane because it has to support certain things like HTML)

The problem I have is (my JEditorPane is called chatLog), when I type chatLog.setContentType("text/html"); and type chatLog.setText("Test");
Nothing happens...

The second I comment out/remove chatLog.setContentType("text/html"); the text that should be appearing, appears fine.

I don't know what i'm doing wrong.

Source:

public ServerGUI() {
    // Rest of code above.

    JEditorPane chatLog = new JEditorPane();
    chatLog.setContentType("text/html");
    chatLog.setEditable(false);

    // Rest of code below.
}

public void appendText(String str) {
    // Can use a word instead of str too like the "Test" above.
    chatLog.setText(chatLog.getText() + str);
    //chatLog.setCaretPosition(chatLog.getText().length() - 1);
}

And also, just another little problem I have which isnt too major, I cant set the caret position as seen above when I have the content type to HTML. It says there is an IllegalArgument Exception

Thanks for the help.


Solution

  • The problem is that you append new text like this:

    chatLog.setText(chatLog.getText() + str);
    

    So you append text to the current content. If you set text/html content type and you never call JEditorPane.setText(), it still has some default HTML code. This default HTML code ends with a proper </html> closing tag. Now if you append anything to an HTML text, that will be after the </html> closing tag so it will not be rendered.

    To demonstrate it:

    JEditorPane chatLog = new JEditorPane();
    chatLog.setContentType("text/html");
    System.out.println(chatLog.getText()); // This will print an HTML document
    

    The empty HTML document has a <body> tag and an empty <p> tag, something like this:

    <html>
      <head>
    
      </head>
      <body>
        <p style="margin-top: 0">
    
        </p>
      </body>
    </html>
    

    Proposed solution:

    Use JEditorPane.getDocument(). If you set text/html content type, by default the returned Document will be an instance of HTMLDocument which you can use to add new elements for new chat messages.