HTML in JTextArea of JEditorPane, JTextPane

Lucas Kauffman picture Lucas Kauffman · May 6, 2011 · Viewed 7.9k times · Source

Right I already worked out that JTextArea or JTextField don't support HTML.

I want to add text to a "screen" like a JTextArea and later keep appending text to it.

I tried with JTextArea which worked wonderfully, but it does not support formatting it seems...

So I tried using JEditorPane's subclass JTextPane, but this one does not have it's append function...

Can someone guid me in the right direction how I easily can append text to a JTextPane or format a JTextArea.

Or if there is any other component better for this please tell me :)

The update method is called by a subject which does this for multiple objects. This just gives a bunch of strings which are formatted and then put in a nice frame to show the user.

@Override
public void update(String channel, String sender, String message) {

    if(channel.equals(this.subject) || sender.equals(subject)){
        StringBuffer b = new StringBuffer();
        b.append("<html>");
        b.append("<b>");
        b.append("</b>");
        b.append("[");
        b.append(sender);
        b.append("] : ");
        b.append("</b>");
        b.append(message);
        b.append("</html>");
        b.append("\n");

        chatArea.append(b.toString());
    }

Answer

camickr picture camickr · May 7, 2011

Can someone guid me in the right direction how I easily can append text to a JTextPane

Document doc = textPane.getDocument();
doc.insertString(doc.getLength(), "some text", green);

And use attributes instead of HTML, its much easier. For example you could define the "green" attributes to be:

SimpleAttributeSet green = new SimpleAttributeSet();
StyleConstants.setForeground(green, Color.GREEN);