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

4

7

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.

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());
} 
Rosendorosene answered 20/10, 2010 at 2:11 Comment(0)
M
9

Update the Document directly:

StyledDocument doc = textPane.getStyledDocument();
doc.insertString("text", doc.getLength(), attributes);
Measured answered 20/10, 2010 at 2:41 Comment(0)
B
5
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!");
Bruiser answered 20/10, 2010 at 2:24 Comment(1)
I understand that, but how would I append text to the end of the document?Rosendorosene
B
1

Ok Take 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 );
Bruiser answered 20/10, 2010 at 2:41 Comment(0)
I
1
JTextPane myTextArea = new JTextPane();
myTextArea.setEditable(false);  
Ivyiwis answered 4/5, 2018 at 15:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.