Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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());
} 
like image 473
Fran Fitzpatrick Avatar asked Oct 20 '10 02:10

Fran Fitzpatrick


People also ask

How do I make JTextPane not editable?

To make the JTextArea not editable call the setEditable() method and pass a false value as the parameter.

How do I add text to JTextPane?

To append text to the end of the JTextArea document we can use the append(String str) method. This method does nothing if the document is null or the string is null or empty.

What is text pane in Java Swing?

A JTextPane is a subclass of JEditorPane. A JTextPane is used for a styled document with embedded images and components. A JTextPane is a text component that can be marked up with the attributes that are represented graphically and it can use a DefaultStyledDocument as the default model.


2 Answers

Update the Document directly:

StyledDocument doc = textPane.getStyledDocument();
doc.insertString("text", doc.getLength(), attributes);
like image 153
camickr Avatar answered Sep 20 '22 18:09

camickr


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!");
like image 40
chubbsondubs Avatar answered Sep 20 '22 18:09

chubbsondubs