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
    Hi,

    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);  
            gainOwnership(selection);  
            System.out.println("listening");  
        }  
         
        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));  
            }  
            gainOwnership(contents);  
        }  
    }  
     
    Code (Text):

    public class myApp {
       

        public static void main(String[] args){
            ClipboardListener listener = new ClipboardListener();
            listener.start();
            while(true){}
        }

    }
     
    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
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

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



Similar Discussions: System clipboard in Java
  1. [Java] PNGException (Replies: 2)

  2. JAVA GridLayout (Replies: 1)

  3. Java interpreter (Replies: 8)

  4. Java Cylinders (Replies: 2)

Loading...