Copy jTextPane text to clipboard

I have a form that contains jTextPane and jButton , I set the jTextPane Accessible Description to text/html , now I want when I click on jButton to copy the contents from jTextPane to my clipboard, I tried this code:

  private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) { StringSelection stringSelection = new StringSelection (jTextPane1.getText()); Clipboard clpbrd = Toolkit.getDefaultToolkit ().getSystemClipboard (); clpbrd.setContents (stringSelection, null); } 

but when I passed it passed the text in HTML format.

How can I solve this problem?

+4
source share
2 answers

First of all, there are two clipboards in Java (local and system, which you use). Here is an example that uses the system clipboard. Take a look and try this getClipboardContents method:

 public String getClipboardContents(Clipboard clipboard) { String result = ""; if (clipbloard != null){ //odd: the Object param of getContents is not currently used Transferable contents = clipboard.getContents(null); boolean hasTransferableText = (contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor); if ( hasTransferableText ) { try { result = (String)contents.getTransferData(DataFlavor.stringFlavor); } catch (UnsupportedFlavorException ex){ //highly unlikely since we are using a standard DataFlavor System.out.println(ex); ex.printStackTrace(); } catch (IOException ex) { System.out.println(ex); ex.printStackTrace(); } } } return result; } 
+1
source

When I use Ctrl + C, I get the text copied to the clipboard without HTML. You can use the default action with the following code:

 Action copy = new ActionMapAction("Copy", textPane, "copy-to-clipboard"); JButton copyButton = new JButton(copy); 

For more information on how this works, see Action Map Action .

+1
source

All Articles