views:

106

answers:

4

I want to set the users clipboard to a string in a Java Console Application. Any ideas?

A: 

there

unbeli
Well I guess a question with no effort or explanation deserves an answer with equal explanation.
TheLQ
+4  A: 

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);
Carlos Heuberger
Note: You need Java 6.
Thorbjørn Ravn Andersen
This does not work.
clone1018
@Thorbjørn - are you sure? why you need Java 6? I'm pretty sure that it works with 1.4.2 (1.1 by javadoc).
Carlos Heuberger
@clone - **it DOES work!**
Carlos Heuberger
@clone - but as I wrote it is a very simplified code - should only be an idea - missing imports, class and method definitions. Have you read the links I posted? And it would be more helpful if you wrote WHAT is not working, and maybe a bit more details of what you want to do (in the question).
Carlos Heuberger
@Carlos, sorry, was thinking of the Desktop class.
Thorbjørn Ravn Andersen
+4  A: 

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);
    }
}
camickr
+1 for SSCCE link and taking the time to write a proper test class. Nicely done.
S.Jones