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

September 2014

S M T W T F S
 123456
78910111213
14 15 1617181920
21222324252627
282930    

Recent Entries

Search My Blog

0 user(s) viewing

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

Categories