Java code Copy String to Clipboard

Java program to Copy String to Clipboard

We can copy the string into clipboard using the below java code. When you execute the java program the clipboard will have the datas in the string "cpdata".

import java.awt.datatransfer.*;
import java.awt.Toolkit;

public final class CopyText implements ClipboardOwner {

public static void main (String arg[]){
CopyText clip = new CopyText();
//display current clipboard data
System.out.println("Current Data:" + clip.getString() );
//Following Context to be copied
String cpdata="This is the sample string to copy clipboard";
System.out.println("New Data:" + clip.getString() );
public void lostOwnership( Clipboard aClipboard, Transferable aContents) {
//do nothing
public void setString(String data){
StringSelection stringSelection = new StringSelection(data);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, this);
public String getString() {
String result = "";
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable contents = clipboard.getContents(null);
boolean hasTransferableText =(contents != null) &&contents.isDataFlavorSupported(DataFlavor.stringFlavor);
if ( hasTransferableText ) {
try {
result = (String)contents.getTransferData(DataFlavor.stringFlavor);
}catch (UnsupportedFlavorException e){
}catch (IOException e) {
return result;

Related Topic PHP Programming Best Practices
Java Download Image from URL
Random Password Generator in Java Example Source Code
Prime Number Program in Java
How to get Hostname IP Address in Java 2011   Privacy Policy  Terms of Service  Feedback