java 将文本添加到 JTextPane 而不让用户编辑?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3974242/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:13:23  来源:igfitidea点击:

Adding text to a JTextPane without having it editable by the user?

javaswingjtextpane

提问by Fran Fitzpatrick

So I've created my own text pane class (extending JTextPane) and I'm using the method below to add text to it. However, the pane needs to be editable for it to add the text, but this allows a user to edit what is in the pane as well.

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

Can anyone tell me how to add text to the pane without letting the user manipulate what is there?

谁能告诉我如何在不让用户操作的情况下向窗格添加文本?

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());
} 

回答by camickr

Update the Document directly:

直接更新文档:

StyledDocument doc = textPane.getStyledDocument();
doc.insertString("text", doc.getLength(), attributes);

回答by chubbsondubs

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!");

回答by chubbsondubs

Ok Take 2:

好的采取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 );

回答by Albert Davies

JTextPane myTextArea = new JTextPane();
myTextArea.setEditable(false);