The following code from a standalone application works in ubuntu:
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransf
I tried your code with debian testing (7.0) and openjdk 7u3. The result is the same, but i think i found the Problem (Solution).
Content in the clipboard is only valid as long as the process exists. It works if i change your code to this:
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
public class ClipboardTest {
public static void main(String[] args) throws Exception {
Clipboard clipBoard = Toolkit.getDefaultToolkit().getSystemClipboard();
// print the last copied thing
Transferable t = clipBoard.getContents(null);
if (t.isDataFlavorSupported(DataFlavor.stringFlavor))
System.out.println(t.getTransferData(DataFlavor.stringFlavor));
StringSelection data = new StringSelection("NOW");
clipBoard.setContents(data, data);
// prints NOW
System.out.println(clipBoard.getContents(null).getTransferData(DataFlavor.stringFlavor));
System.in.read();
}
}
The if statement prevent your code from throwing an exception when there is no usable content, which happens if you run your code once and the process ends.
The System.in.read() just keeps the process alive. While not press enter i can paste into another application and "NOW" comes out as expected.
Like this the code works every time for me.
Hope this helps.