how-to

Others - Clipboard

How to copy/paste image into/from clipboard

For this example you need to use:

import java.awt.datatransfer.*;

For copying string into clipboard is situation easy - because in JDK exists java.awt.datatransfer.StringSelection class. This class implements Transferable interface for string object.

For images similar class doesn`t exists, so we must implement it first.

First step - create object for transfering images (=implements Transferable interface)

static class TransferableImage implements Transferable {

  /* -- image for transfer */
    
  private Image image;

  /* -- constructor */
    
  public TransferableImage( Image image ) {
    this.image = image;
  }

  /* -- when is performed check for image type, returns image */
    
  @Override
  public Object getTransferData( DataFlavor flavor ) throws UnsupportedFlavorException {
    if ( isDataFlavorSupported( flavor ) ) {
      return image;
    } else {
      throw new UnsupportedFlavorException( flavor );
    }
  }

  /* -- method for checking supported type */
    
  @Override
  public boolean isDataFlavorSupported( DataFlavor flavor ) {
    return flavor == DataFlavor.imageFlavor;
  }

  /* -- get supported type */
    
  @Override
  public DataFlavor[] getTransferDataFlavors() {
    return new DataFlavor[]{ DataFlavor.imageFlavor };
  }
}

Now is possible copy an image into clipboad.

COPY part

For copy an image into clipboard use this code. For copying is used our new TransferableImage class.

/* -- read image, here from project resources */
    
Image image = Toolkit.getDefaultToolkit().getImage( this.getClass().getResource( "resource\\lock.gif" ) );
          
/* -- transfer image into clipboard */
    
TransferableImage transferable = new TransferableImage( image );
Toolkit.getDefaultToolkit().getSystemClipboard().setContents( transferable, null );

PASTE part

For paste image from clipboard use this code:

/* -- get clipboard content */

Transferable transferable = Toolkit.getDefaultToolkit().getSystemClipboard().getContents( null );

/* -- check, if contains image. If yes, try to get it */

if ( transferable != null && transferable.isDataFlavorSupported( DataFlavor.imageFlavor ) ) {
        
  try {
    Image image = (Image)transferable.getTransferData( DataFlavor.imageFlavor );

    //this.getGraphics().drawImage( image, 100, 200, null );
  }
  catch (UnsupportedFlavorException ex) {
    Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
  } catch (IOException ex) {
    Logger.getLogger(Window.class.getName()).log(Level.SEVERE, null, ex);
  }

}