Skip to content

Commit 06dd02f

Browse files
authored
[BAEL-6602] Copying text to clipboard in Java (#18656)
1 parent 0ad250d commit 06dd02f

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

core-java-modules/core-java-swing/pom.xml

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
<?xml version="1.0" encoding="UTF-8"?>
22
<project xmlns="http://maven.apache.org/POM/4.0.0"
3-
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4-
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
3+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4+
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
55
<modelVersion>4.0.0</modelVersion>
66
<artifactId>core-java-swing</artifactId>
77
<packaging>jar</packaging>
@@ -19,4 +19,8 @@
1919
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
2020
</properties>
2121

22+
<build>
23+
<sourceDirectory>src/main/java</sourceDirectory>
24+
</build>
25+
2226
</project>
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
package com.baeldung.clipboard;
2+
3+
import java.awt.Toolkit;
4+
import java.awt.datatransfer.Clipboard;
5+
import java.awt.datatransfer.StringSelection;
6+
import java.awt.datatransfer.Transferable;
7+
import java.awt.datatransfer.UnsupportedFlavorException;
8+
import java.io.IOException;
9+
import java.awt.datatransfer.DataFlavor;
10+
11+
public class AwtClipboard {
12+
13+
public static void main(String[] args) throws IOException, UnsupportedFlavorException {
14+
String textToCopy = "Baeldung helps developers explore the Java ecosystem and simply be better engineers.";
15+
copyToClipboard(textToCopy);
16+
17+
String textCopied = copyFromClipboard();
18+
if (textCopied != null) {
19+
System.out.println(textCopied);
20+
}
21+
}
22+
23+
public static void copyToClipboard(String text) {
24+
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
25+
StringSelection data = new StringSelection(text);
26+
cb.setContents(data, null);
27+
}
28+
29+
public static String copyFromClipboard() throws UnsupportedFlavorException, IOException {
30+
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
31+
Transferable transferable = cb.getContents(null);
32+
if (transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) {
33+
String data = (String) transferable.getTransferData(DataFlavor.stringFlavor);
34+
return data;
35+
}
36+
System.out.println("Couldn't get data from the clipboard");
37+
return null;
38+
}
39+
}

0 commit comments

Comments
 (0)