Tuesday, April 24, 2012

Clipboard monitoring on Mac OS X | Java

I'm having troubles getting data from the system clipboard on Mac OS X.
What I'm trying to do is to listen to the system clipboard and print the content of the clipboard each time new [text based] information is put into it.



The problem: bellow code works perfectly fine on Windows 7 and openSuse Linux machines, however when I try running the same code on Mac OS X the program fails to print the new content of the clipboard until focus is given to the application. [Nothing is printed until I click on the application icon on the dock...]



My source code:



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);
}

public void gainOwnership(Transferable t){
try {this.sleep(100);}
catch (InterruptedException e) {e.printStackTrace();}
systemClipboard.setContents(t, this);
}

public void lostOwnership(Clipboard clipboard, Transferable contents) {
try {System.out.println((String) clipboard.getData(DataFlavor.stringFlavor));}
catch (UnsupportedFlavorException e) {}
catch (IOException e) {}
gainOwnership(contents);
}
}





public class myApp {

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

}


What I'm missing/doing wrong?



[Update]
I found similar problem posted here: Java thread goes to sleep when not in focus on OSX
However using the command "java -jar myApp.jar &" didn't work as a workaround for me.





No comments:

Post a Comment