Java JTextPane 追加一个新字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4059198/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JTextPane appending a new string
提问by Dmitry
In an every article the answer to a question "How to append a string to a JEditorPane?" is something like
在每篇文章中,“如何将字符串附加到 JEditorPane?”这个问题的答案。就像
jep.setText(jep.getText + "new string");
I have tried this:
我试过这个:
jep.setText("<b>Termination time : </b>" +
CriterionFunction.estimateIndividual_top(individual) + " </br>");
jep.setText(jep.getText() + "Processes' distribution: </br>");
And as a result I got "Termination time : 1000" without "Processes' distribution:"
结果我得到了“终止时间:1000”而没有“进程分布:”
Why did this happen???
为什么会这样???
采纳答案by 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.
我怀疑这是附加文本的推荐方法。这意味着每次更改某些文本时都需要重新解析整个文档。人们可能这样做的原因是因为他们不了解如何使用 JEditorPane。这包括我。
I much prefer using a JTextPane and then using attributes. A simple example might be something like:
我更喜欢使用 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); }
回答by Istao
setText is to set all text in a textpane. Use the StyledDocumentinterface to append, remove, ans so on text.
setText 是设置文本窗格中的所有文本。使用StyledDocument界面来附加、删除、解析文本。
txtPane.getStyledDocument().insertString(
offsetWhereYouWant, "text you want", attributesYouHope);
回答by Brandon Buck
A JEditorPane
, just a like a JTextPane
has a Document
that you can use for inserting strings.
A JEditorPane
,就像 aJTextPane
有一个Document
可以用来插入字符串。
What you'll want to do to append text into a JEditorPane is this snippet:
要将文本附加到 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();
}
}
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.
我对此进行了测试,对我来说效果很好。这doc.getLength()
是您想要插入字符串的位置,显然使用这一行您会将其添加到文本的末尾。