Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

System clipboard in Java

  1. Apr 16, 2012 #1

    I'm trying to get familiar with the system clipboard by building a "clipboard listener" what I want to do is listen to the clipboard and when it changed print the new value that is put into the clipboard[if it is text].

    This is what I tried:

    Code (Text):

    import java.awt.Toolkit;  
    import java.awt.datatransfer.*;  
    import java.io.IOException;  
    public class ClipboardListener extends Thread implements ClipboardOwner {  
        Clipboard systemClipboard = Toolkit.getDefaultToolkit().getSystemClipboard();  
        public void run(){  
            Transferable selection = systemClipboard.getContents(this);  
        public void gainOwnership(Transferable t){  
            System.out.println("gain ownership");  
            systemClipboard.setContents(t, this);  
        public void lostOwnership(Clipboard clipboard, Transferable contents) {  
            System.out.println("lost ownership");  
            if (contents.isDataFlavorSupported(DataFlavor.stringFlavor)){  
                    System.out.println((string) contents.getTransferData(DataFlavor.stringFlavor));  
    Code (Text):

    public class myApp {

        public static void main(String[] args){
            ClipboardListener listener = new ClipboardListener();

    Now 2 strange things happen:
    1. lostOwnership never runs if I run the code in Mac OS X [it does if I run it in Windows 7].
    2. From some reason I get an exception while I'm trying to print what has changed within the clipboard, in lostOwnership.
    Last edited: Apr 16, 2012
  2. jcsd
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Can you offer guidance or do you also need help?
Draft saved Draft deleted