Subscribe to Tethik's Blag        RSS Feed
-----

How to append to a HTML JEditorPane

Icon Leave Comment
Let's say we wanted to append a String "text" to a JEditorPane, making sure that any html is parsed:
String text = "<p> Example </p>";


I've found two ways to do it.

The simple but bad way:
JEditorPane pane = new JEditorPane("text/html", null);
pane.setText(pane.getText() + text);


This is bad because you're parsing the whole text again and then adding your String at the end.
Appending should only involve adding our String to the end of the text.

The better way
JEditorPane pane = new JEditorPane("text/html", null);
HTMLEditorKit editor = pane.getEditor();
StringReader reader = new StringReader(text);

try {
  editor.read(reader, pane.getDocument(), pane.getDocument().getLength());
}
catch(BadLocationException ex) {
   //This happens if your offset is out of bounds.
}
catch (IOException ex) {
  // I/O error
}


This way you skip the unnecessary reparsing.

Sources:
Javadoc for HTMLEditorKit.read

0 Comments On This Entry

 

Trackbacks for this entry [ Trackback URL ]

There are no Trackbacks for this entry

August 2015

S M T W T F S
      1
2345678
9101112131415
16171819202122
2324252627 28 29
3031     

Recent Entries

Search My Blog

0 user(s) viewing

0 Guests
0 member(s)
0 anonymous member(s)

Categories