Java copy to clipboard

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

Rate article
ASJAVA.COM
Add a comment

Your email address will not be published. Required fields are marked *

*

code

  1. Xavier

    Thanks! I’ve been looking for something easy to understand for about 3 hours now !

    Reply
    1. admin author

      Thanks, good to know it helped.

      Reply
  2. tomek

    Good stuff, thanks. Nice and simple and clipboard learnt.

    Reply
  3. Ryan

    I need a simple way of emptying the clipboard contents??

    Reply
    1. admin author

      See the code below
      public static void clearClipboard() {
      try {
      clipboard().setContents(new Transferable() {
      public DataFlavor[] getTransferDataFlavors() {
      return new DataFlavor[0];
      }

      public boolean isDataFlavorSupported(DataFlavor flavor) {
      return false;
      }

      public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {
      throw new UnsupportedFlavorException(flavor);
      }
      }, null);
      } catch (IllegalStateException e) {}
      }

      Reply