187

I want to copy text from a JTable's cell to the clipboard, making it available to be pasted into other programs such as Microsoft Word. I have the text from the JTable, but I am unsure how to copy it to the clipboard.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
user765134
  • 1,873
  • 2
  • 12
  • 4

7 Answers7

343

This works for me and is quite simple:

Import these:

import java.awt.datatransfer.StringSelection;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;

And then put this snippet of code wherever you'd like to alter the clipboard:

String myString = "This text will be copied into clipboard";
StringSelection stringSelection = new StringSelection(myString);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(stringSelection, null);
Denis Abakumov
  • 355
  • 3
  • 11
Pangolin
  • 7,284
  • 8
  • 53
  • 67
  • 1
    we can setContents() with owner too http://stackoverflow.com/questions/3591945/copying-to-clipboard-in-java – Aquarius Power Mar 12 '16 at 20:39
  • @AquariusPower It seems that passing `stringSelection` as the 2nd argument to `setContents(..)` too, making it the `ClipboardOwner`, as in the linked answer, has no significance: looking at the [source](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/8u40-b25/java/awt/datatransfer/StringSelection.java#StringSelection.lostOwnership%28java.awt.datatransfer.Clipboard%2Cjava.awt.datatransfer.Transferable%29), the sole method of `ClipboardOwner` that it implements, namely, `lostOwnership(..)`, is empty. So, the 2nd argument seems to be a completely optional callback. – Evgeni Sergeev Jun 03 '16 at 03:18
  • @EvgeniSergeev it may be useful if we extend StringSelection :) – Aquarius Power Jun 03 '16 at 18:36
  • 3
    Ported to Clojure: `(-> (java.awt.Toolkit/getDefaultToolkit) .getSystemClipboard (.setContents (java.awt.datatransfer.StringSelection. "test") nil))` – NikoNyrh Aug 26 '17 at 10:23
  • In which context did you test this? From a GUI application? On which platform? Does it work setting the clipboard 100 times in a row (with some appropriate pause between each set)? – Peter Mortensen Feb 09 '18 at 22:28
34

This is the accepted answer written in a decorative way:

Toolkit.getDefaultToolkit()
        .getSystemClipboard()
        .setContents(
                new StringSelection(txtMySQLScript.getText()),
                null
        );
Wesos de Queso
  • 1,526
  • 1
  • 21
  • 23
21

The following class allows you to copy/paste a String to/from the clipboard.

import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;

import static java.awt.event.KeyEvent.*;
import static org.apache.commons.lang3.SystemUtils.IS_OS_MAC;

public class SystemClipboard
{
    public static void copy(String text)
    {
        Clipboard clipboard = getSystemClipboard();
        clipboard.setContents(new StringSelection(text), null);
    }

    public static void paste() throws AWTException
    {
        Robot robot = new Robot();

        int controlKey = IS_OS_MAC ? VK_META : VK_CONTROL;
        robot.keyPress(controlKey);
        robot.keyPress(VK_V);
        robot.keyRelease(controlKey);
        robot.keyRelease(VK_V);
    }

    public static String get() throws Exception
    {
        Clipboard systemClipboard = getSystemClipboard();
        DataFlavor dataFlavor = DataFlavor.stringFlavor;

        if (systemClipboard.isDataFlavorAvailable(dataFlavor))
        {
            Object text = systemClipboard.getData(dataFlavor);
            return (String) text;
        }

        return null;
    }

    private static Clipboard getSystemClipboard()
    {
        Toolkit defaultToolkit = Toolkit.getDefaultToolkit();
        return defaultToolkit.getSystemClipboard();
    }
}
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185
9

For JavaFx based applications.

        //returns System Clipboard
        final Clipboard clipboard = Clipboard.getSystemClipboard();
        // ClipboardContent provides flexibility to store data in different formats
        final ClipboardContent content = new ClipboardContent();
        content.putString("Some text");
        content.putHtml("<b>Some</b> text");
        //this will be replaced by previous putString
        content.putString("Some different text");
        //set the content to clipboard
        clipboard.setContent(content);
       // validate before retrieving it
        if(clipboard.hasContent(DataFormat.HTML)){
            System.out.println(clipboard.getHtml());
        }
        if(clipboard.hasString()){
            System.out.println(clipboard.getString());
        }

ClipboardContent can save multiple data in several data formats like(html,url,plain text,image).

For more information see official documentation

gprasadr8
  • 789
  • 1
  • 8
  • 12
3

I found a better way of doing it so you can get a input from a txtbox or have something be generated in that text box and be able to click a button to do it.!

import java.awt.datatransfer.*;
import java.awt.Toolkit;

private void /* Action performed when the copy to clipboard button is clicked */ {
    String ctc = txtCommand.getText().toString();
    StringSelection stringSelection = new StringSelection(ctc);
    Clipboard clpbrd = Toolkit.getDefaultToolkit().getSystemClipboard();
    clpbrd.setContents(stringSelection, null);
}

// txtCommand is the variable of a text box
3

For reference:

static void copyToClipboard(String text) {
    java.awt.Toolkit.getDefaultToolkit().getSystemClipboard()
        .setContents(new java.awt.datatransfer.StringSelection(text), null);
}
sahlaysta
  • 95
  • 1
  • 3
0

For reference here are the copy and paste functions from/to the system clipboard written in Clojure (so related to Java):


(defn copy [s]
  (-> (java.awt.Toolkit/getDefaultToolkit)
      .getSystemClipboard
      (.setContents (java.awt.datatransfer.StringSelection. s) nil)))

(defn paste []
  (-> (java.awt.Toolkit/getDefaultToolkit)
      .getSystemClipboard
      (.getContents nil)
      (.getTransferData java.awt.datatransfer.DataFlavor/stringFlavor)))

(copy "Hello!")
(paste) ;=> "Hello!"

Jérémie
  • 360
  • 5
  • 6