首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >JTextPane追加新字符串

JTextPane追加新字符串
EN

Stack Overflow用户
提问于 2010-10-30 22:49:03
回答 3查看 96.4K关注 0票数 35

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

代码语言:javascript
复制
jep.setText(jep.getText + "new string");

我已经尝试过了:

代码语言:javascript
复制
jep.setText("<b>Termination time : </b>" + 
                        CriterionFunction.estimateIndividual_top(individual) + " </br>");
jep.setText(jep.getText() + "Processes' distribution: </br>");

结果我得到了“终止时间: 1000”,而没有“进程的分布:”

为什么会发生这样的事情?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2010-10-30 23:32:43

我怀疑这是附加文本的推荐方法。这意味着每次更改某些文本时,都需要重新解析整个文档。人们这样做的原因是因为他们不知道如何使用JEditorPane。包括我在内。

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

代码语言:javascript
复制
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); }
票数 68
EN

Stack Overflow用户

发布于 2010-11-03 04:22:16

就像JTextPane一样,JEditorPane有一个可以用来插入字符串的Document

要将文本附加到JEditorPane中,您需要执行以下代码片段:

代码语言:javascript
复制
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()是您想要插入字符串的位置,显然,使用此行可以将其添加到文本的末尾。

票数 27
EN

Stack Overflow用户

发布于 2010-10-30 23:26:46

setText用于设置文本窗格中的所有文本。使用StyledDocument接口添加、删除等文本。

代码语言:javascript
复制
txtPane.getStyledDocument().insertString(
  offsetWhereYouWant, "text you want", attributesYouHope);
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4059198

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档