I’m using the Robot class in Java to copy Strings from other programs. This works correctly, provided I don’t set the contents of the clipboard programmatically before attempting to copy. Setting the contents of the clipboard seems to prevent Java from seeing changes to the clipboard made by other programs.
The copied content is actually in the clipboard. This can be tested by pasting into notepad or another text window. However, getting the contents of the clipboard in Java returns the previously set value, not the copied value.
try {
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(new StringSelection("empty"), null);
Robot robot = new Robot();
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_A);
robot.keyRelease(KeyEvent.VK_CONTROL);
robot.delay(50);
robot.keyPress(KeyEvent.VK_CONTROL);
robot.keyPress(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_C);
robot.keyRelease(KeyEvent.VK_CONTROL);
String currentContents = clipboard.getContents(null).getTransferData(DataFlavor.stringFlavor).toString();
System.out.println(currentContents);
} catch (AWTException | UnsupportedFlavorException | IOException e) {
e.printStackTrace();
}