Search code examples
javaswingjeditorpane

Java Swing JEditorPane: manipulating styled documents


I have model that is a queue of Strings associated with enum types.

I'm trying to display that model in a JEditorPane, with each element in the queue as a separate HTML paragraph that has attributes based based on the associated enum type.

However, my updating methods are not doing what I want. I tried writing the HTML strings directly to the document (e.g., I take the Strings, prepend <p style="color:red"> and append </p> and then insert them at the end of the document), but that gives me the html tags in the output (instead of as formatting) - which of course is inconsistent with the result of putting the tags on the string that I use construct the document with JEditorPane("text/html",String foo). I've also tried inserting with an AttributeSet, but apparently I'm doing that wrong as well.

Any suggestions?


Solution

  • I've never had much luck playing with HTML in a JEditorPane. I just use attributes in a JTextPane. Something like:

    SimpleAttributSet keyWord = new SimpleAttributeSet();
    StyleConstants.setForeground(keyWord, Color.RED);
    StyleConstants.setBackground(keyWord, Color.YELLOW);
    StyleConstants.setBold(keyWord, true);
    
    try
    {
        doc.insertString(doc.getLength(), "\nSome more text", keyWord );
    }
    catch(Exception e) {}