We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
IndexProgramming Questions & HelpSyntax Questions › Paste from Clipboard
Page Index Toggle Pages: 1
Paste from Clipboard (Read 422 times)
Paste from Clipboard
Sep 29th, 2009, 2:37am
 
Hello

I was searching for a simple method to paste a string from the clipboard into my Processing App. Unfortunately I didn't find anything, so I hacked something together myself.
It worked in OS X Leopard with Processing 1.0.3.

Better methods and corrections are appreciated.

Cheers

Code:

import java.awt.datatransfer.*;

Clipboard clipboard = getToolkit().getSystemClipboard();
boolean comKey;
int comKeyCode = 157;  // on Mac: 157   // on Windows: ???

void setup()
{
 size(600, 300);
 background(128);
 frameRate(25);
}

void draw()
{
}

void keyPressed()
{
if(keyCode == comKeyCode) comKey = true;
if(key == 'v' && comKey == true) println(getClipboard());
}

void keyReleased()
{
 if(keyCode == comKeyCode) comKey = false;
}


String getClipboard()
{
String s = "";
 Transferable clipData = clipboard.getContents(clipboard);
 if (clipData != null) {
   try {
     if (clipData.isDataFlavorSupported (DataFlavor.stringFlavor)) {
       s = (String)(clipData.getTransferData(
       DataFlavor.stringFlavor));
     }
   }
   catch (UnsupportedFlavorException ufe) {
     System.err.println("Flavor unsupported: " + ufe);
   }
   catch (IOException ioe) {
     System.err.println("Data not available: " + ioe);
   }
 }
 return s;
}

Page Index Toggle Pages: 1