Nathan Howard Nathan is a Java/HTML5 developer. Nathan also enjoys writing technical blog-articles and playing games in his spare time.

Tutorial : How To Copy Text in JavaFX and Swing

1 min read

At IDRSolutions we have a PDF Viewer that has the ability to highlight and copy text, because we are developing a JavaFX implementation of our PDF Viewer we required a way to copy text in JavaFX that does not use the Swing libraries.

In this tutorial I will show you how to Copy text to the System clipboard in JavaFX and how to do the same in Swing for comparison.

ss


Copying Text in JavaFX

Copying text in JavaFX is a simple process, it requires the import of the following classes :

import javafx.scene.input.Clipboard;
import javafx.scene.input.ClipboardContent;

All we need to do now is to get the String of text that needs copying, this can be from anywhere really but for this example we’ll grab it from a TextField.

String copyText = myTextField.getText();

Now we create a ClipboardContent object which allows us to hold the string of text and a Clipboard object which will allow us to copy the text passed to ClipboardContent to the System Clipboard.

final Clipboard clipboard = Clipboard.getSystemClipboard();
final ClipboardContent content = new ClipboardContent();
content.putString(copyText);
clipboard.setContent(content);

And that’s it! Common cases of this would be to put inside some form of Action Listener.

Copying Text in Swing

Copying text in Swing is a similar process to JavaFX, it requires the following classes:

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

All we need to do now is to get the String of text that needs copying, this can be from anywhere really but for this example we’ll grab it from a JTextField.

String copyText = myJTextField.getText();

Now we pass the String into a StringSelection object which then gets set as the content of the System Clipboard.

StringSelection ss = new StringSelection(copyText);
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);

And that’s it! Common cases of this would be to put inside some form of Listener/Handler.

Thank you for reading, I hope you enjoyed this article and will find it of use. If you have any questions, please post them in the comments section bellow.

You may find some of my other JavaFX articles of interest :

Grab our JavaFX PDF Viewer plugin for NetBeans.



Our software libraries allow you to

Convert PDF files to HTML
Use PDF Forms in a web browser
Convert PDF Documents to an image
Work with PDF Documents in Java
Read and write HEIC and other Image formats in Java
Nathan Howard Nathan is a Java/HTML5 developer. Nathan also enjoys writing technical blog-articles and playing games in his spare time.