2010-10-20 48 views
6

因此,我创建了自己的文本窗格类(扩展JTextPane),并使用下面的方法向其添加文本。但是,该窗格需要可编辑才能添加文本,但这也允许用户编辑窗格中的内容。将文本添加到JTextPane而不让用户编辑它?

谁能告诉我如何添加文本到窗格而不让用户操纵那里?

public void appendColor(Color c, String s) { 
    StyleContext sc = StyleContext.getDefaultStyleContext(); 
    AttributeSet aset = sc.addAttribute(SimpleAttributeSet.EMPTY, StyleConstants.Foreground, c); 

    int len = getDocument().getLength(); 

    setCaretPosition(len); 

    setCharacterAttributes(aset, false); 

    replaceSelection(s); 

    setCaretPosition(getDocument().getLength()); 
} 

回答

6

更新直接在文档:

StyledDocument doc = textPane.getStyledDocument(); 
doc.insertString("text", doc.getLength(), attributes); 
3
JTextPane pane = new JTextPane(); 
pane.setEditable(false); // prevents the user from editting it. 
// programmatically put this text in the TextPane 
pane.setText("Hello you can't edit this!"); 
+0

我明白,但我会如何文本追加到文档的结束? – 2010-10-20 02:26:03

0

确定以2:

JTextPane pane = new JTextPane(); 
pane.setEditable(true); 
DefaultStyledDocument document = (DefaultStyledDocument)pane.getDocument(); 
document.insertString("Hello you can't edit this!", document.getEndPosition().getOffset(), null); 
相关问题