JTextPane appending a new string

Dmitry picture Dmitry · Oct 30, 2010 · Viewed 94.2k times · Source

In an every article the answer to a question "How to append a string to a JEditorPane?" is something like

jep.setText(jep.getText + "new string");

I have tried this:

jep.setText("<b>Termination time : </b>" + 
                        CriterionFunction.estimateIndividual_top(individual) + " </br>");
jep.setText(jep.getText() + "Processes' distribution: </br>");

And as a result I got "Termination time : 1000" without "Processes' distribution:"

Why did this happen???

Answer

camickr picture camickr · Oct 30, 2010

I doubt that is the recommended approach for appending text. This means every time you change some text you need to reparse the entire document. The reason people may do this is because the don't understand how to use a JEditorPane. That includes me.

I much prefer using a JTextPane and then using attributes. A simple example might be something like:

JTextPane textPane = new JTextPane();
textPane.setText( "original text" );
StyledDocument doc = textPane.getStyledDocument();

//  Define a keyword attribute

SimpleAttributeSet keyWord = new SimpleAttributeSet();
StyleConstants.setForeground(keyWord, Color.RED);
StyleConstants.setBackground(keyWord, Color.YELLOW);
StyleConstants.setBold(keyWord, true);

//  Add some text

try
{
    doc.insertString(0, "Start of text\n", null );
    doc.insertString(doc.getLength(), "\nEnd of text", keyWord );
}
catch(Exception e) { System.out.println(e); }