在每一篇文章中,回答一个问题“如何将字符串追加到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”,而没有“进程的分布:”
为什么会发生这样的事情?
发布于 2010-10-30 23:32:43
我怀疑这是附加文本的推荐方法。这意味着每次更改某些文本时,都需要重新解析整个文档。人们这样做的原因是因为他们不知道如何使用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-11-03 04:22:16
就像JTextPane一样,JEditorPane有一个可以用来插入字符串的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();
}
}我测试了一下,它对我来说工作得很好。doc.getLength()是您想要插入字符串的位置,显然,使用此行可以将其添加到文本的末尾。
发布于 2010-10-30 23:26:46
setText用于设置文本窗格中的所有文本。使用StyledDocument接口添加、删除等文本。
txtPane.getStyledDocument().insertString(
offsetWhereYouWant, "text you want", attributesYouHope);https://stackoverflow.com/questions/4059198
复制相似问题