JTextPane appending a new string

狂风中的少年 提交于 2019-11-26 20:08:15
camickr

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); }

A JEditorPane, just a like a JTextPane has a Document that you can use for inserting strings.

What you'll want to do to append text into a JEditorPane is this snippet:

JEditorPane pane = new JEditorPane();
/* ... Other stuff ... */
public void append(String s) {
   try {
      Document doc = pane.getDocument();
      doc.insertString(doc.getLength(), s, null);
   } catch(BadLocationException exc) {
      exc.printStackTrace();
   }
}

I tested this and it worked fine for me. The doc.getLength() is where you want to insert the string, obviously with this line you would be adding it to the end of the text.

setText is to set all text in a textpane. Use the StyledDocument interface to append, remove, ans so on text.

txtPane.getStyledDocument().insertString(
  offsetWhereYouWant, "text you want", attributesYouHope);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!