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 & HelpIntegration › Windows Clipboard
Page Index Toggle Pages: 1
Windows Clipboard (Read 1401 times)
Windows Clipboard
Jun 29th, 2006, 11:50pm
 
Does anyone know how to get a Processing program and/or applet to read from/read to the Windows Clipboard?
Re: Windows Clipboard
Reply #1 - Jun 30th, 2006, 7:40am
 
// //////////////////
// Clipboard class for Processing
// by seltar  
// v 0115
// only works with programs. applets require signing

class ClipHelper
{
 Clipboard clipboard;
 ClipHelper()
 {
   getClipboard();  
 }
 
 void getClipboard ()
 {
   // this is our simple thread that grabs the clipboard
   Thread clipThread = new Thread() {
public void run() {
  clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
}
   };

   // start the thread as a daemon thread and wait for it to die
   if (clipboard == null) {
try {
  clipThread.setDaemon(true);
  clipThread.start();
  clipThread.join();
}  
catch (Exception e) {
}
   }
 }

 void copyString (String data)
 {
   copyTransferableObject(new StringSelection(data));
 }

 void copyTransferableObject (Transferable contents)
 {
   getClipboard();
   clipboard.setContents(contents, null);
 }

 String pasteString ()
 {
   String data = null;
   try {
data = (String)pasteObject(DataFlavor.stringFlavor);
   }  
   catch (Exception e) {
System.err.println("Error getting String from clipboard: " + e);
   }

   return data;
 }

 Object pasteObject (DataFlavor flavor)  
   throws UnsupportedFlavorException, IOException
 {
   Object obj = null;
   getClipboard();

   Transferable content = clipboard.getContents(null);
   if (content != null)
obj = content.getTransferData(flavor);

   return obj;
 }
}


// Usage
import java.awt.datatransfer.*;

PFont dFont;
ClipHelper cp = new ClipHelper();

boolean[] keys = new boolean[526];
boolean checkKey(String k)
{
 for(int i = 0; i < keys.length; i++)
   if(KeyEvent.getKeyText(i).toLowerCase().equals(k.toLowerCase())) return keys[i];  
 return false;
}

void setup()
{
 size(500,400);
 dFont = loadFont("ArialMT-48.vlw");
 textFont(dFont,12);
 background(0);
}

void draw()
{
}

void keyPressed()
{ keys[keyCode] = true;
 if(checkKey("ctrl") && checkKey("v")) background(Integer.parseInt(cp.pasteString()));
 if(checkKey("ctrl") && checkKey("c")) cp.copyString(""+(int)random(255));
}

void keyReleased()
{ keys[keyCode] = false; }
Page Index Toggle Pages: 1