Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying to the clipboard in Java [duplicate]

I want to set the user's clipboard to a string in a Java console application. Any ideas?

like image 894
clone1018 Avatar asked Aug 28 '10 18:08

clone1018


2 Answers

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); 
like image 100
user85421 Avatar answered Nov 15 '22 15:11

user85421


Here is a simple SSCCE to accomplish this:

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);     } } 
like image 45
camickr Avatar answered Nov 15 '22 15:11

camickr