JTextPane附加一个新字符串

Dmi*_*try 33 java swing jtextpane styleddocument

在每篇文章中回答一个问题"如何将字符串附加到JEditorPane?" 是这样的

jep.setText(jep.getText + "new string");
Run Code Online (Sandbox Code Playgroud)

我试过这个:

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

结果我得到了"终止时间:1000"而没有"进程分发":

为什么会这样?

cam*_*ckr 64

我怀疑这是附加文本的推荐方法.这意味着每次更改某些文本时,都需要重新整理整个文档.人们可能这样做的原因是因为不了解如何使用JEditorPane.那包括我.

我更喜欢使用JTextPane然后使用属性.一个简单的例子可能是这样的:

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); }
Run Code Online (Sandbox Code Playgroud)

  • 这将重新创建文档并丢失您之前添加的所有自定义属性. (3认同)
  • @Dmitry结合setText + getText来追加可能被认为是草率的编程.(我个人用它来进行简单的测试.)例如,如果我要使用该方法维护一个日志文件,那么每次附加日志条目时都必须构建一个新的String(这是一个非常糟糕的主意,因为字符串是不可变的.)这可能最终会导致明显的内存占用. (2认同)
  • 很好的例子,但没有回答将文本附加到JEditorPane的问题. (2认同)

Bra*_*uck 26

A JEditorPane,就像a JTextPane有一个Document你可以用来插入字符串.

要将文本附加到JEditorPane中,您要做的是这个片段:

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();
   }
}
Run Code Online (Sandbox Code Playgroud)

我测试了这个,它对我来说很好.这doc.getLength()是您要插入字符串的位置,显然使用此行您可以将其添加到文本的末尾.