Clipboard contents can't be set by java

MidnightJava

Registered
I have a java program that sets the contents of the system clipboard. It's a very simple task, and it works fine on my Windows machine. But on OSX it doesn't seem to work. I set the contents and the program doesn't throw an Exception. Furthermore I can read the contents of the clipboard from my program and see the contents that I wrote to it. But all the other OSX applications don't see any change to the clipboard. Whatever was on the clipboard before the java program accessed it is still there.

I can't believe that the clipboard on OSX is this broken and I'm the first one to discover it. But it's clearly not working as advertised, and I can't find any reference to a relevant bug on Sun's java site. I posted a question on Sun's java forum but haven't got any responses. I'm posting here because I think it's an OS integration issue and not a java problem. As far as the jvm is concerned, the clipboard contents have been changed. It's just that other applications don't see it that way. Could the jvm be obtaining a different instance of the system clipboard than the other applications are using?

Here's my java code.


Code:
String cbText = sw.toString();
		
Clipboard sysCB = Toolkit.getDefaultToolkit().getSystemClipboard();
		
System.err.println("clipboard text: " + cbText);
//cbText prints as expected
		
StringSelection ss = new StringSelection(cbText);
		
try{
	sysCB.setContents(ss, ss);
}
catch (Exception e){
		e.printStackTrace();
}
//no Exception thrown
//clipboard contents as viewed from any other app are unchanged


//now I do some further checking to prove that the clipboard contents
//were changed as far as the jvm is concerned

String cbText2 = "";
		
try {
     cbText2= (String)sysCB.getContents(null).getTransferData(DataFlavor.stringFlavor);
} catch (UnsupportedFlavorException e1) {

	e1.printStackTrace();
} catch (IOException e1) {
			e1.printStackTrace();
}
		
System.err.println("clipboard text after setContents() = " + cbText2);

//cbText2 contents are same as cbText
 
I found the reason the clipboard write was not working properly. I was executing the application via ssh login, and in this context the awt toolkit apparently has no access to the system clipboard. It would have been nice if Toolkit.getSystemClipboard() had returned null. Instead it returned a Clipboard object that had no reference or relationship to the system clipboard.
 
Back
Top