madhu
madhu

Reputation: 37

Jtextpane copy coloured text and paste

I have a JTextPane which displays colored text . I use the followong piece of code to get text from JTextPane.

String temp = pane.getDocument().getText(0,pane.getDocument().getLength());

However when i try to set the temp variable content to pane again,

pane.select(0,pane.getDocument().getLength());
pane.replaceSelection(temp);

by this way i lose the color and get white text. Is there anyway where i can maintain the color of text without copying the content to clipboard.

Please help.

Upvotes: 1

Views: 939

Answers (1)

StanislavL
StanislavL

Reputation: 57421

Actually it depends on EditorKit you use. The first part returns text (with styled info) of the selected fragment. E.g. in the RTFEditorKit it would be rtf content of the document's fragment.

The second part is not correct. Replace selection can't process the content properly. I guess in case of the RTFEditorKit it would be all the text with formatting inserted in the pane.

I would use

pane.setText(temp);

instead. If you need to insert the styled fragment use kit.read(...) passing the temp in the call

You can try the Kit as alternative of the default RTFEditorKit and see what happens

UPDATE: Sorry original comment was incorrect a bit. The code should be

 pane.getEditorKit().read(
      new StringReader(temp), 
      pane.getDocument(), 
      pane.getDocument().getLength())

Upvotes: 2

Related Questions