The clipboard is a set of functions and messages that enables applications to transfer data each other, Java implements the mechanism to transfer data using cut/copy/paste operations. This chapter demonstrate some examples about coping data to clipboard, clearing clipboard and reading existing clipboard contents.

Java have system clipboard and local Clipboard, system clipboard is more commonly and widely used, local Clipboard is only visible for single application or specified program.

An example that Java copy a string to clipboard

ClipboardExample.java
import java.awt.*;

import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;

/**
* Copy a String on the clipboard.
*/
public void copyStringToClipboard(String str) {
  StringSelection stringSelection = new StringSelection(str);
  Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
  clipboard.setContents(stringSelection, null);
}

It gets the System Clipboard from the default Toolkit. then creates a String Selection from the input and sets the contents of the Clipboard with the String Selection.

An example that Java get contents from clipboard

ClipboardExample.java
import java.awt.*;

import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;

/**
* Get a String contents from the clipboard.
*/
public String getStringClipboard() throws UnsupportedFlavorException, IOException {
  Transferable t = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
  if (t != null && t.isDataFlavorSupported(DataFlavor.stringFlavor)) {
    String text = (String) t.getTransferData(DataFlavor.stringFlavor);
    return text;
  }
  return null;
}