6

因此,我创建了自己的文本窗格类(扩展 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());
} 
4

4 回答 4

9

直接更新文档:

StyledDocument doc = textPane.getStyledDocument();
doc.insertString("text", doc.getLength(), attributes);
于 2010-10-20T02:41:05.780 回答
4
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!");
于 2010-10-20T02:24:37.863 回答
1

好的采取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 );
于 2010-10-20T02:41:39.257 回答
1
JTextPane myTextArea = new JTextPane();
myTextArea.setEditable(false);  
于 2018-05-04T15:39:37.730 回答