how-to

Others - Clipboard

How to copy/paste string into/from clipboard

For this example you need to use:

import java.awt.datatransfer.*;

COPY part

For copy string into clipboard use this code:

/* -- get system clipboard */

Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

/* -- set clipboard content (string data) */

StringSelection str = new StringSelection( "This is some text" );
clipboard.setContents( str, null );

PASTE part

For paste string from clipboard use this code:

/* -- get system clipboard */

Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();

/* -- get clipboard context */

Transferable data = clipboard.getContents(null);

/* -- is context string type ? */

boolean bIsText = ( ( data != null ) && ( data.isDataFlavorSupported( DataFlavor.stringFlavor ) ) );

/* -- if yes, translate context to string type and write it */

if ( bIsText ) {

  try {

    String s = (String)data.getTransferData( DataFlavor.stringFlavor );

    System.out.println( s );

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

}

The output will be:

This is some text