Results 1 to 12 of 12
Thread: Clipboard and jTextPane
- 12-30-2008, 08:50 AM #1
Member
- Join Date
- Nov 2008
- Posts
- 42
- Rep Power
- 0
Clipboard and jTextPane
Hi there
I'm looking for a pro in datatransfer.
I'm trying to create method to copy and paste the content of a jTextPane in another one. I was planning to use the Clipboard to do so.
But, there is a few things that I can't figure out.
1. I need a class that implements Transferable and ClipboardOwner and it's an instance of this class that will be sent to the Clipboard. Right?
2. How this class should be? I'm planning to make it DefaultStyledDocumentSelection and my DataFlavor would be DefaultStyledDocument.
3. Now I need to create a Clipboard object. Should I make a local Clipboard or get the System Clipboard. I read in an article of 1998 that the System Clipboard could only store plain text. Does it changes? Which one is better to support my DefaultStyledDocumentSelection I create?
That's it for the moment.
- 12-30-2008, 05:00 PM #2
I just glanced through the API.
You should use Toolkit.getDefaultToolkit().getSystemClipboard() to get access to the system clipboard.
Transferable and ClipboardOwner are interfaces, so you *could* implement your own version. However, StringSelection implements both, so that seems to make more sense. If you can capture your text area contents as a String, even if it contains some form of formatting information, you can put that on the clipboard using StringSelection.
DataFlavors are MIME types, but I would suggest staying away from that.
The Clipboard object fires events, so you will have to listen to them. That is probably a good way for the receiver to find out that the sender put some information on the clipboard.
The problem with this approach is that the user can user the clipboard for other purposes in other applications, so you may run into conflicts.
I hope this gets you moving in the right direction.
I assume that the text areas are in different VM's. Otherwise, just have the classes communicate directly. Even if they are in different VM's, using a temporary file or a socket connection might be more reliable.
- 12-30-2008, 05:59 PM #3
For an older example see reply 2 of Cut/copy/paste with style information intact.
- 12-30-2008, 11:05 PM #4
Member
- Join Date
- Nov 2008
- Posts
- 42
- Rep Power
- 0
Thx for the reply.
I guess my original post was not completely clear. I'm using a jTextPane because I have a Document with differents style in it. The class StringSelection only transfer plain text data. So the style in my Document wouldn't come with it.
Unfortunately, I think StringSelection is the only out of the box Dataflavor that come with Java. If you want to transfer other type of data you will need to create your own dataflavor. (I can't completely avoid the mimeType)
But, this example might be useful.
Thx for the help.
Gudradain
- 01-02-2009, 06:42 AM #5
Member
- Join Date
- Nov 2008
- Posts
- 42
- Rep Power
- 0
Alright I work this part out. But now I'm in the next part :eek:
I want to make it possible to copy a text from Microsoft Word to my JTextPane. To do it, my JTextPane need to have a compatible dataflavor with Microsoft Word and this flavor need to keep the style attributes intact.
Here is a list of some dataflavor Microsoft Word supports: (I know it's big)
- java.awt.datatransfer.DataFlavor[mimetype=application/x-java-text-encoding;representationclass=[B]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.io.Reader]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.lang.String]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.nio.CharBuffer]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=[C]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.io.InputStream;chars et=UTF-16]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.nio.ByteBuffer;chars et=UTF-16]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=[B;charset=UTF-16]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.io.InputStream;chars et=UTF-8]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.nio.ByteBuffer;chars et=UTF-8]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=[B;charset=UTF-8]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.io.InputStream;chars et=UTF-16BE]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.nio.ByteBuffer;chars et=UTF-16BE]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=[B;charset=UTF-16BE]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.io.InputStream;chars et=UTF-16LE]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.nio.ByteBuffer;chars et=UTF-16LE]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=[B;charset=UTF-16LE]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.io.InputStream;chars et=ISO-8859-1]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.nio.ByteBuffer;chars et=ISO-8859-1]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=[B;charset=ISO-8859-1]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.io.InputStream;chars et=windows-1252]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.nio.ByteBuffer;chars et=windows-1252]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=[B;charset=windows-1252]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.io.InputStream;chars et=US-ASCII]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=java.nio.ByteBuffer;chars et=US-ASCII]
- java.awt.datatransfer.DataFlavor[mimetype=text/html;representationclass=[B;charset=US-ASCII]
- java.awt.datatransfer.DataFlavor[mimetype=text/rtf;representationclass=java.io.InputStream]
- java.awt.datatransfer.DataFlavor[mimetype=text/rtf;representationclass=java.nio.ByteBuffer]
- java.awt.datatransfer.DataFlavor[mimetype=text/rtf;representationclass=[B]
- java.awt.datatransfer.DataFlavor[mimetype=application/x-java-serialized-object;representationclass=java.lang.String]
I don't feel like implementing every dataflavor in my program so maybe there is one specific that could do it.
Any idea which one I should choose?
N.B. String is already supported by my program but it can't transfer the Styles
- 01-02-2009, 07:10 AM #6
You can find out how to create a custom DataFlavor that works with native applications on Using and Creating a DataFlavor.
- 01-02-2009, 08:07 AM #7
Member
- Join Date
- Nov 2008
- Posts
- 42
- Rep Power
- 0
Last edited by Gudradain; 01-02-2009 at 08:15 AM.
- 01-04-2009, 12:44 AM #8
My notebook has MS Works but not MS Word.
I did some exploring to see what's available.
It seems that the type we need to work with would be:
but I don't have access to it.Java Code:Rich\ Text\ Format=text/rtf nativeStr = Rich\ Text\ Format mimeStr = text/rtf flavor = null mimeType = null JAVA_DATAFLAVOR:text/rtf isJavaMIMEType = true Rich\ Text\ Format 0
Since we are working on the Java side of things and since MS apps won't have a clue what to do with Java classes I would try to find out how the rich text formatting/styles are applied and then write an InputStream class that can send the data that the MS target can use. And one that can receive the MS clipboard data and translate it into Java. You might be able to pick up the trail for rich text at their MSDN site.
Here's the SystemFlavorMap exploration:
Java Code:import java.awt.datatransfer.*; import java.io.*; import java.util.*; public class FlavorRx { public static void main(String[] args) { //showFlavormapPropertiesFile(); String[] strs = exploreSystemFlavorMap(); tryAgain(strs); } private static String[] exploreSystemFlavorMap() { List<String> nativeStrs = new ArrayList<String>(); SystemFlavorMap flavorMap = (SystemFlavorMap)SystemFlavorMap.getDefaultFlavorMap(); String path = "C:/jdk1.6.0_03/jre/lib/flavormap.properties"; BufferedReader br = null; try { br = new BufferedReader( new InputStreamReader( new FileInputStream(path))); String line; while((line = br.readLine()) != null) { if(line.length() == 0 || line.charAt(0) == '#') { continue; } System.out.println(line); int firstEquals = line.indexOf("="); String nativeStr = line.substring(0, firstEquals); String mimeStr = line.substring(firstEquals+1); System.out.printf("nativeStr = %s mimeStr = %s%n", nativeStr, mimeStr); nativeStrs.add(nativeStr); DataFlavor flavor = null; try { flavor = SystemFlavorMap.decodeDataFlavor(nativeStr); } catch(ClassNotFoundException e) { System.out.println("cnfe: " + e.getMessage()); } System.out.println("flavor = " + flavor); String mimeType = SystemFlavorMap.decodeJavaMIMEType(nativeStr); System.out.println("mimeType = " + mimeType); String encoded = SystemFlavorMap.encodeJavaMIMEType(mimeStr); System.out.printf("%s isJavaMIMEType = %b%n", encoded, flavorMap.isJavaMIMEType(encoded)); List<DataFlavor> list = flavorMap.getFlavorsForNative(nativeStr); System.out.println(nativeStr + " " + list.size()); for(int i = 0; i < list.size(); i++) { System.out.printf("%2d %s%n", i, list.get(i)); } System.out.println("----------------------------"); } br.close(); } catch(IOException e) { System.out.println("i/o error: " + e.getMessage()); } return nativeStrs.toArray(new String[nativeStrs.size()]); } private static void tryAgain(String[] strs) { System.out.println("----------- tryAgain ------------"); SystemFlavorMap flavorMap = (SystemFlavorMap)SystemFlavorMap.getDefaultFlavorMap(); Map<String, DataFlavor> map = flavorMap.getFlavorsForNatives(strs); System.out.println("map size = " + map.size()); Iterator it = map.keySet().iterator(); while(it.hasNext()) { Object key = it.next(); DataFlavor flavor = map.get(key); System.out.printf("key = %s\nflavor = %s%n", key, flavor); System.out.println("----------------------------"); } } private static void showFlavormapPropertiesFile() { // path to your installed jre/ String path = "C:/jdk1.6.0_03/jre/lib/flavormap.properties"; BufferedReader br = null; try { br = new BufferedReader( new InputStreamReader( new FileInputStream(path))); String line; while((line = br.readLine()) != null) { System.out.println(line); } br.close(); } catch(IOException e) { System.out.println("i/o error: " + e.getMessage()); } } }
- 01-04-2009, 01:14 AM #9
Member
- Join Date
- Nov 2008
- Posts
- 42
- Rep Power
- 0
Thx a lot hardwired.
I'm going to check how the rich text format are applied.
- 01-04-2009, 02:07 AM #10
Member
- Join Date
- Nov 2008
- Posts
- 42
- Rep Power
- 0
I already did some work with mime type text/html.
I create a TransferHandler that support text/html;class=java.lang.String. This way I'm able to get the html code representation of MS Word. Putting this data in a html file I create a JTextPane that keep some of the style information intact.
The problem is that the StyledDocument associated with my JTextPane is now useless.
You can check it by yourself
Here is the fileLoaderJava Code:import javax.swing.JTextPane; import javax.swing.JFrame; import javax.swing.JScrollPane; import java.awt.BorderLayout; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import javax.swing.text.BadLocationException; import javax.swing.TransferHandler; import javax.swing.JComponent; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.StringSelection; //Was in use before import java.awt.datatransfer.Transferable; import java.awt.datatransfer.Clipboard; import javax.swing.text.Element; import javax.swing.text.SimpleAttributeSet; import javax.swing.text.html.HTMLEditorKit; //Import for StringTransferSelection import java.awt.datatransfer.ClipboardOwner; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; import javax.swing.text.DefaultStyledDocument; public class JTextPaneHTMLTransfer { public static void main(String [] args){ //1.a -- Create a jFrame JFrame myFrame = new JFrame("MyTextEditor"); myFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); //1.b – Create your jTextPane and add it to the frame JTextPane myTextPane = new JTextPane(); myTextPane.setTransferHandler(new JTextPaneHTMLTransferHandler()); JScrollPane myScrollPane = new JScrollPane(myTextPane); myFrame.add(myScrollPane, BorderLayout.CENTER); //1.c - Show the frame myFrame.setSize(400,300); //or myFrame.pack(); myFrame.setVisible(true); } } class JTextPaneHTMLTransferHandler extends TransferHandler{ DataFlavor htmlFlavor = DataFlavor.stringFlavor; public JTextPaneHTMLTransferHandler(){ System.out.println("Constructor of TransferHandler"); try{ htmlFlavor = new DataFlavor("text/html;class=java.lang.String"); }catch (Exception e){ System.out.println("Flavor creation failed"); } } public void exportToClipboard(JComponent comp, Clipboard clip, int action) { System.out.println("method exportToClipboard"); super.exportToClipboard(comp, clip, action); } public int getSourceActions(JComponent c) { System.out.println("method getSourceActions"); return COPY_OR_MOVE; } protected Transferable createTransferable(JComponent c){ System.out.println("method createTransferable"); JTextPane aTextPane = (JTextPane)c; String textString = aTextPane.getSelectedText(); return new StringSelection(textString); } public boolean canImport(JComponent comp, DataFlavor[] transferFlavors){ System.out.println("method canImport"); System.out.println(htmlFlavor); System.out.println(); boolean retour = false; for(int i=0; i<transferFlavors.length; i++){ System.out.println(transferFlavors[i]); if(htmlFlavor.equals(transferFlavors[i])){ retour = true; } } return retour; } public boolean importData(JComponent comp, Transferable t){ System.out.println("method importData"); if(canImport(comp, t.getTransferDataFlavors())){ System.out.println("canImport is true"); String transferString = ""; try{ transferString = (String)t.getTransferData(htmlFlavor); }catch (Exception e){ System.out.println("transferString failed"); } JTextPane srcTextPane = (JTextPane)comp; srcTextPane.setText(transferString); return true; } System.out.println("canImport is false"); return false; } }
Java Code:import javax.swing.JTextPane; import javax.swing.JFrame; import javax.swing.JScrollPane; import java.awt.BorderLayout; import javax.swing.text.Style; import javax.swing.text.StyleConstants; import javax.swing.text.StyledDocument; import javax.swing.text.BadLocationException; import java.lang.Thread; public class LoadJTextPaneHTML { public static void main(String [] args){ //1.a -- Create a jFrame JFrame myFrame = new JFrame("MyTextEditor"); myFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); //1.b – Create your jTextPane and add it to the frame JTextPane myTextPane = new JTextPane(); JScrollPane myScrollPane = new JScrollPane(myTextPane); myFrame.add(myScrollPane, BorderLayout.CENTER); //1.c - Show the frame myFrame.setSize(400,300); //or myFrame.pack(); myFrame.setVisible(true); try{ myTextPane.setPage("file:///C:/Program%20Files/Crimson%20Editor/template/Text2.html"); }catch (Exception e){ System.out.println("setPage Exception"); } //Wait for loading time try{ Thread.currentThread().sleep(10000); }catch (Exception e){ System.out.println("Thread exception"); } StyledDocument myStyledDocument = myTextPane.getStyledDocument(); String content = ""; try{ content = myStyledDocument.getText(0, myStyledDocument.getLength()); }catch (Exception e){ System.out.println("Error in get content with document"); } System.out.println("NO ERROR"); System.out.println("STYLED DOCUMENT CONTENT"); System.out.println(content); content = myTextPane.getText(); System.out.println("\nTEXTPANE CONTENT\n"); System.out.println(content); //1.a -- Create a jFrame JFrame aFrame = new JFrame("NewTextEditor"); myFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE); //1.b – Create your jTextPane and add it to the frame JTextPane aTextPane = new JTextPane(myStyledDocument); JScrollPane aScrollPane = new JScrollPane(aTextPane); aFrame.add(aScrollPane, BorderLayout.CENTER); //1.c - Show the frame aFrame.setSize(400,300); //or myFrame.pack(); aFrame.setVisible(true); System.out.println("End of method"); } }Last edited by Gudradain; 01-04-2009 at 02:15 AM. Reason: Forget some code in LoadJTextPaneHTML
- 01-04-2009, 05:41 PM #11
You can check it by yourself
I will need to see your file "Text2.html"
- 01-04-2009, 11:08 PM #12
Member
- Join Date
- Nov 2008
- Posts
- 42
- Rep Power
- 0
Sorry
I get my file Text2.html wiht the class JTextPaneHTMLTransfer. If MS Works support the DataFlavor text/html;class=java.lang.String you will be able to get a similar Document by performing a copy/cut operation in MS Works then pasting it in the JTextPane of JTextPaneHTMLTransfer.
I don't have MS Works so I can't tell what DataFlavor are supported by it but you can find it using the class JTextPaneHTMLTransfer. A list of all the DataFlavor available in MS Works will be print in the output (System.out.print) if you performed the copy in MS Works and paste in the JTextPane. You can get the list of DataFlavor of any programs this way.
Anyway here is my file Text2.html (the content is in French...)
Also, by changing a few lines of code in JTextPaneHTMLTransfer I create a class that could transfer the DataFlavor text/rtf;java.io.InputStreamXML Code:<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40"> <head> <meta http-equiv=Content-Type content="text/html; charset=utf-8"> <meta name=ProgId content=Word.Document> <meta name=Generator content="Microsoft Word 9"> <meta name=Originator content="Microsoft Word 9"> <link rel=File-List href="file:///C:/DOCUME~1/Marc/LOCALS~1/Temp/msoclip1/01/clip_filelist.xml"> <!--[if gte mso 9]><xml> <w:WordDocument> <w:View>Normal</w:View> <w:Zoom>0</w:Zoom> <w:HyphenationZone>21</w:HyphenationZone> <w:DoNotOptimizeForBrowser/> </w:WordDocument> </xml><![endif]--> <style> <!-- /* Font Definitions */ @font-face {font-family:"Adobe Caslon Pro Bold"; panose-1:0 0 0 0 0 0 0 0 0 0; mso-font-charset:0; mso-generic-font-family:roman; mso-font-format:other; mso-font-pitch:variable; mso-font-signature:7 1 0 0 147 0;} @font-face {font-family:"Bookshelf Symbol 7"; panose-1:5 1 1 1 1 1 1 1 1 1; mso-font-charset:2; mso-generic-font-family:auto; mso-font-pitch:variable; mso-font-signature:0 268435456 0 0 -2147483648 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:""; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:"Times New Roman"; mso-fareast-font-family:"Times New Roman";} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} --> </style> </head> <body lang=FR style='tab-interval:35.4pt'> <!--StartFragment--><span lang=FR-CA style='font-size:12.0pt;font-family: "Times New Roman";mso-fareast-font-family:"Times New Roman";mso-ansi-language: FR-CA;mso-fareast-language:FR;mso-bidi-language:AR-SA'>BONJOUR TOI. </span><span lang=FR-CA style='font-size:12.0pt;font-family:"Adobe Caslon Pro Bold"; mso-fareast-font-family:"Times New Roman";mso-bidi-font-family:"Times New Roman"; mso-ansi-language:FR-CA;mso-fareast-language:FR;mso-bidi-language:AR-SA'>J’essai de créer un JTextPane qui </span><i><span lang=FR-CA style='font-size:12.0pt; font-family:"Bookshelf Symbol 7";mso-fareast-font-family:"Times New Roman"; mso-bidi-font-family:"Times New Roman";mso-ansi-language:FR-CA;mso-fareast-language: FR;mso-bidi-language:AR-SA'>peut transférer le contenu de n?importe quel program en gardant le style du document intact</span></i><span lang=FR-CA style='font-size:12.0pt;font-family:"Times New Roman";mso-fareast-font-family: "Times New Roman";mso-ansi-language:FR-CA;mso-fareast-language:FR;mso-bidi-language: AR-SA'>.</span><!--EndFragment--> </body> </html>
The part I'm stuck with now is how to make it possible for your JTextPane to interpret correctly the data in HTML and rtf Format. I'm going to check the EditorKits for that.
Similar Threads
-
Copy from Clipboard in japplet
By AZMichael in forum Java AppletsReplies: 3Last Post: 09-06-2008, 02:30 PM -
How to copy and paste data with the clipboard
By Java Tip in forum SWTReplies: 0Last Post: 07-07-2008, 04:35 PM -
SWT Clipboard Example
By Java Tip in forum SWTReplies: 0Last Post: 07-07-2008, 04:34 PM -
Using the clipboard
By Java Tip in forum java.awt.datatransferReplies: 0Last Post: 04-16-2008, 10:52 PM -
Sending Image Objects through the Clipboard
By Java Tip in forum java.awt.datatransferReplies: 0Last Post: 04-16-2008, 10:52 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks