Copying Text to the Clipboard Using Java

Copying text to the clipboard using Java

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);

How to copy text/html and text/plain to clipboard using Java

So, after a little bit of playing around (and reading the updated JavaDocs). The basic answer is.

  1. You need to supply both a "plain text" and "html text" value
  2. You need to supply multiple data flavours, each representing the type of data you're willing to export
  3. You need to return the appropriate data from getTransferData based on the flavour (and the flavours desired export method)

Please Note

This example exports two different strings, one is plain text and one is HTML, this is deliberate, so as it's easier to see when different text is used by different consumers. You could, obviously, use the html formatted text for both if you wished.

Sample Image

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.util.ArrayList;
import java.util.List;

public final class Main {
public static void main(String[] args) {

String plainText = "Hello World";
String htmlText = "<html><body><h1>This is a test</h1></body></html>";

HtmlSelection htmlSelection = new HtmlSelection(htmlText, plainText);
Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
clipboard.setContents(htmlSelection, null);
}

public static class HtmlSelection implements Transferable {

private static List<DataFlavor> htmlFlavors = new ArrayList<>(3);

static {
htmlFlavors.add(DataFlavor.stringFlavor);
htmlFlavors.add(DataFlavor.allHtmlFlavor);
}

private String html;
private String plainText;

public HtmlSelection(String html, String plainText) {
this.html = html;
this.plainText = plainText;
}

public DataFlavor[] getTransferDataFlavors() {
return (DataFlavor[]) htmlFlavors.toArray(new DataFlavor[htmlFlavors.size()]);
}

public boolean isDataFlavorSupported(DataFlavor flavor) {
return htmlFlavors.contains(flavor);
}

public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException {

String toBeExported = plainText;
if (flavor == DataFlavor.stringFlavor) {
toBeExported = plainText;
} else if (flavor == DataFlavor.allHtmlFlavor) {
toBeExported = html;
}

if (String.class.equals(flavor.getRepresentationClass())) {
return toBeExported;
}
throw new UnsupportedFlavorException(flavor);
}
}
}

You should also beware that some applications may prefer a different method of export (ie via a Reader or InputStream), this is demonstrated in...

  • Copy jTable row with its grid lines into excel/word documents
  • Copy JTextArea as "text/html" DataFlavor

How to Copy multiple text line in clipboard and paste in another non java form

We use a Scanner to traverse through the lines of code. Then we set the next line to the clipboard and press Ctrl + V to paste the data using the Robot class. After clicking your JButton you have 5 seconds to click into the wanted text box. It will then start pasting and tabbing.

There are some sleep(...) statements in there because I don't know the UI you are working with it better save than sorry and give it some time to react.

import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionEvent;
import java.util.Scanner;

import static java.awt.event.KeyEvent.*;

// ...

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
String multiLineText = jTextField1.getText()+"\n"+jTextField2.getText()+"\n"+jTextField3.getText()+"\n"+jTextField4.getText()+"\n"+jTextField5.getText();
Scanner textReader = new Scanner(multiLineText);
Robot r = new Robot();

System.out.println("You have 5 seconds to focus the text box into which the text will be pasted!");

for (int i = 0; i < 5; i++) {
System.out.println(5 - i + "...");
Thread.sleep(1000);
}
System.out.println("Start pasting...");
while (textReader.hasNext()) {
String line = textReader.nextLine().trim();
System.out.println("\t> Pasting \"" + line + "\"");

Toolkit.getDefaultToolkit()
.getSystemClipboard()
.setContents(
new StringSelection(line),
null);

pressKeys(r, VK_CONTROL, VK_V);
pressKeys(r, VK_TAB);
}

} catch (AWTException | InterruptedException ex) {
throw new RuntimeException(ex);
}
}

public static void pressKeys(Robot robot, int... keys) throws InterruptedException {
for (int i = 0; i < keys.length; i++) {
robot.keyPress(keys[i]);
Thread.sleep(10);
}
for (int i = 0; i < keys.length; i++) {
robot.keyRelease(keys[keys.length - i - 1]);
Thread.sleep(10);
}
Thread.sleep(100);
}

Can Java system clipboard copy a file?

Essentially, yes. You need to remember that both the drag'n'drop API and the clipboard API use the same concept of a Transferable, which wraps the data into DataFlavors, so you can transfer the data differently based on the flavor the target system would like to use

Generally, when transferring files, Java uses a java.util.List and a DataFlavor.javaFileListFlavor. Unfourtantly, there's no nice "wrapper" class available for this, so you'll need to provide your own, for example...

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Test {

public static void main(String[] args) {
File file = new File("/path/to/your/file");
List listOfFiles = new ArrayList();
listOfFiles.add(file);

FileTransferable ft = new FileTransferable(listOfFiles);

Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ft, new ClipboardOwner() {
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
System.out.println("Lost ownership");
}
});
}

public static class FileTransferable implements Transferable {

private List listOfFiles;

public FileTransferable(List listOfFiles) {
this.listOfFiles = listOfFiles;
}

@Override
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[]{DataFlavor.javaFileListFlavor};
}

@Override
public boolean isDataFlavorSupported(DataFlavor flavor) {
return DataFlavor.javaFileListFlavor.equals(flavor);
}

@Override
public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
return listOfFiles;
}
}

}

In my tests, I was able to place a File in the List, wrap into a Transferable, pass it to the Clipboard and was able to paste the file through the system (Windows Explorer)

Copy text to clipboard from a JTextfield with press of a button

You can copy the text with the following code

StringSelection stringSelection = new StringSelection (txtField.getText());
Clipboard clpbrd = Toolkit.getDefaultToolkit ().getSystemClipboard ();
clpbrd.setContents (stringSelection, null);

The text will be copied to your clip board and then it can be pasted anywhere. In any editor.

Read more about Clipboard, Toolkit, StringSelection

I Hope you know how to import packages/classes in Java

Hint

As you want to copy text in a Text Field, you can add the above code in actionPerformed() method of you ActionListener.



Related Topics



Leave a reply



Submit