Clipboard
How do I put a String to system clipboard and read data from it ?
[65 byte] By [
mdenis] at [2007-11-15 19:13:10]

# 1 Re: Clipboard
Hi,
Use the below one to get the System Clipboard.
Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
Using the Clipboard class you can set the contents or get the contents in the clip board.
You have to use the following classes.
DataFlavor and Clipboard classes and Transferable interface for getting the contents.
For setting the contents you have to use StringSelection class in addition or a class which implements Transferable and Clipboardowner interfaces.
These classes are found in Java 2 in java.awt.datatransfer package.
Here is code to get the contents of the clipboard. Before running this program you should have some contents in your clip board.
import java.awt.*;
import java.awt.datatransfer.*;
public class Clip{
public static void main(String[] args){
try{
Clip c = new Clip();
Clipboard cp = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable tr = cp.getContents(c);
System.out.println((String)tr.getTransferData(DataFlavor.stringFlavor));
}catch(Exception e){
System.out.println(e);
}
}
}//End of class
For detail explanation see Java docs for 1.2
Hope it will solve your problem.
Regards,
arun...
# 2 Re: Clipboard
Thanks, that really works. And what about putting a String there ? I've done it this way:
String s = "The string to put to clipboard"
JTextArea jta = new JTextArea(s);
jta.selectAll();
jta.copy();
...but it's rather patch than a solution.
mdenis at 2007-11-10 3:02:45 >

# 3 Re: Clipboard
After copying into your clipboard, call
Toolkit.getDefaultToolkit().getSystemClipboard() to get the Clipboard and then do the things to get it.
Hope understood this time. If not reply.
# 5 Re: Clipboard
Actually I misunderstood your question in my last reply.
if you want to enter a string directly, you have to use the StringSelection class.
Create an object of StringSelection class with the string u want to input and then
call the setContents(Transeferable,ClipboardOwner) of the Clipboard class.
/*
Clipboard cp = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection select = new StringSelection("Java");
cp.setContents(select,select);
*/
Use this.
Reply me if any problems.