Hi everybody!

Is there a way to compy an Image to the clipboard. I think you need to use Toolkit and transferable.


I did this once in my text editor. It was for text, but the code my help out a little:

imported statements for transerfable:

import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.awt.Toolkit;

get an instance of the system clipboard

Clipboard clipboard = getToolkit().getSystemClipboard();

Some method required for the interface:

   * Empty implementation of the ClipboardOwner interface.
   public void lostOwnership( Clipboard aClipboard, Transferable aContents) {
     //do nothing

set the contents of the clipboard

clipboard.setContents(data, this);

Paste something from the clipboard

int lastPosition = textArea2.getSelectionEnd();
	 /*  get the contents of the clipboard
	 Transferable clipData = clipboard.getContents(this);
	 /* try to paste it where the cursor is
	  String s;
   if (clipData != null)
      try {
        s = (String)(clipData.getTransferData(DataFlavor.stringFlavor));
      catch (Exception e) {
        s = e.toString();

Note: Don't forget to implement the ClipboardOwner interface
Also, the code should almost be exactly the same except for a few details.

what is "data?" is it an image, a Transferable,, etc?


Data is the string. Remember, this was for my text editor. I believe you can put any object in as the data.

When I put an Image instead of data, i get errors. I didn't do anyting with ClipboardOwner, though. Am I missing something?

Here's the error message i get:

"paint.java": setContents(java.awt.datatransfer.Transferable,java.awt.datatransfer.ClipboardOwner) in java.awt.datatransfer.Clipboard cannot be applied to (java.awt.image.BufferedImage,paint) at line 109, column 17


Sorry, Data is actually the transferable.

Here's the signature for the method:

setContents(Transferable contents, ClipboardOwner owner)

how do you make the string (or the image, in my case), a transferable?


thanx, server_crash! that link really helped. i got the program running.

This article has been dead for over six months. Start a new discussion instead.