这是indexloc提供的服务,不要输入任何密码
Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions core-java-modules/core-java-swing/pom.xml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<artifactId>core-java-swing</artifactId>
<packaging>jar</packaging>
Expand All @@ -19,4 +19,8 @@
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<build>
<sourceDirectory>src/main/java</sourceDirectory>
</build>

</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
package com.baeldung.clipboard;

import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.awt.datatransfer.DataFlavor;

public class AwtClipboard {

public static void main(String[] args) throws IOException, UnsupportedFlavorException {
String textToCopy = "Baeldung helps developers explore the Java ecosystem and simply be better engineers.";
copyToClipboard(textToCopy);

String textCopied = copyFromClipboard();
if (textCopied != null) {
System.out.println(textCopied);
}
}

public static void copyToClipboard(String text) {
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
StringSelection data = new StringSelection(text);
cb.setContents(data, null);
}

public static String copyFromClipboard() throws UnsupportedFlavorException, IOException {
Clipboard cb = Toolkit.getDefaultToolkit().getSystemClipboard();
Transferable transferable = cb.getContents(null);
if (transferable.isDataFlavorSupported(DataFlavor.stringFlavor)) {
String data = (String) transferable.getTransferData(DataFlavor.stringFlavor);
return data;
}
System.out.println("Couldn't get data from the clipboard");
return null;
}
}