Code - CopyPasteTool.pde
I found a simple tutorial over on Java Practices that demonstrated the use of the system clipboard for transferring text between applications using copy / paste. I'm using it to copy color values from an improved version of SimpleColorPicker.pde.
The CopyPaste class described in the code can be dropped into any Processing sketch to provide access to the clipboard.
Source code - CopyPasteTool.pde
// CopyPasteTool.pde // Marius Watz - http://workshop.evolutionzone.com // // Code for transferring strings via the clipboard using copy / paste. // Useful for simple inter-app communication. // Java classes needed for copy / paste functions. import java.awt.datatransfer.*; CopyPaste copypaste; void setup() { copypaste=new CopyPaste(); } void keyPressed() { // If 'c' is pressed the Hex string for the current color is copied // to the clipboard. if(key=='c') transfer.sendString("Test "+(int)random(1000)); if(key=='v') println("From the clipboard: '"+transfer.getString()+"'"); } // // The following code provide for sending and receiving strings // via the system clipboard using standard copy / paste. This class // can be copied into any Processing sketch, ready for use. // // Based on code found at http://www.javapractices.com/Topic82.cjp class CopyPaste implements ClipboardOwner { public void sendString(String s) { StringSelection stringSelection = new StringSelection( s ); Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); clipboard.setContents( stringSelection, this ); } public String getString() { String str=""; Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard(); Transferable contents = clipboard.getContents(null); boolean hasTransferableText = (contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor); if(hasTransferableText) { try {str=(String)contents.getTransferData(DataFlavor.stringFlavor); } catch (Exception ex){ System.out.println("Exception: "+ex.toString()); ex.printStackTrace(); str=" "; } } return str; } // Necessary method, but does nothing public void lostOwnership( Clipboard clip, Transferable data) { //do nothing } }




