35

すべての記事で、「JEditorPaneに文字列を追加する方法」という質問への回答があります。のようなものです

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

私はこれを試しました:

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

その結果、「プロセスの配布:」なしで「終了時間:1000」を取得しました。

なぜこれが起こったのですか?

4

3 に答える 3

68

それがテキストを追加するための推奨されるアプローチではないかと思います。つまり、テキストを変更するたびに、ドキュメント全体を再解析する必要があります。人々がこれを行う理由は、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); }
于 2010-10-30T15:32:43.247 に答える
27

JEditorPaneと同じように、JTextPane文字Document列の挿入に使用できるがあります。

JEdi​​torPaneにテキストを追加するために実行したいのは、次のスニペットです。

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

私はこれをテストしました、そしてそれは私のためにうまくいきました。これdoc.getLength()は、文字列を挿入する場所です。明らかに、この行を使用して、テキストの最後に文字列を追加します。

于 2010-11-02T20:22:16.170 に答える
4

setTextは、すべてのテキストをテキストペインに設定します。StyledDocumentインターフェイスを使用して、テキストの追加、削除などを行います。

txtPane.getStyledDocument().insertString(
  offsetWhereYouWant, "text you want", attributesYouHope);
于 2010-10-30T15:26:46.377 に答える