I want to set the users clipboard to a string in a Java Console Application. Any ideas?
Use the Toolkit to get the System Clipboard.
Create a StringSelection with the string and add it to the Clipboard.
Simplified:
StringSelection selection = new StringSelection(theString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(selection, selection);
This article is a little older but their method may work better: http://www.javaworld.com/cgi-bin/mailto/x_java.cgi?pagetosend=/export/home/httpd/javaworld/javaworld/javatips/jw-javatip61.html&pagename=/javaworld/javatips/jw-javatip61.html&pageurl=http://www.javaworld.com/javaworld/javatips/jw-javatip61.html&site=jw_core (link is for print version so you can see the entire article at once).
This does not work.
That tells us nothing about your problem. If you write code and you think it doesn't work then post your SSCCE that demonstrates it doesn't work, because that code works for the rest of us.
Here is a simple SSCCE for future reference:
import java.awt.*;
import java.awt.datatransfer.*;
import java.io.*;
class ClipboardTest
{
public static void main(String[] args)
throws UnsupportedFlavorException, IOException
{
Clipboard c = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection testData;
// Add some test data
if (args.length > 0)
testData = new StringSelection( args[0] );
else
testData = new StringSelection( "Test Data" );
c.setContents(testData, testData);
// Get clipboard contents, as a String
Transferable t = c.getContents( null );
if ( t.isDataFlavorSupported(DataFlavor.stringFlavor) )
{
Object o = t.getTransferData( DataFlavor.stringFlavor );
String data = (String)t.getTransferData( DataFlavor.stringFlavor );
System.out.println( "Clipboard contents: " + data );
}
System.exit(0);
}
}