Code / Program

by Vinoth 2009-03-03 20:00:01

The bellow code will help us to copy a block of content into clip board and get the existing content from clip board.
import java.awt.datatransfer.*;
import java.awt.Toolkit;
import java.io.*;

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
clip.setString("hiox.org");
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){
System.out.println(e);
}
catch (IOException e) {
System.out.println(e);
}
}
return result;
}
}

Tagged in:

4735
like
3
dislike
1
mail
flag

You must LOGIN to add comments