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);
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
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();
}
}
This is the accepted answer written in a decorative way:
Toolkit.getDefaultToolkit()
.getSystemClipboard()
.setContents(
new StringSelection(txtMySQLScript.getText()),
null
);