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.
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 :
- How to Change Color Space from Swing to JavaFX
- How to Change the Mouse Cursor in JavaFX
- How to Setup Key Combinations in JavaFX
- How to Create Stacked Menus in JavaFX
- How to Create a Border Glow Effect in JavaFX.
Grab our JavaFX PDF Viewer plugin for NetBeans.
Are you a Developer working with PDF files?
Our developers guide contains a large number of technical posts to help you understand the PDF file Format.
Find out more about our software for Developers
|Convert PDF to HTML5 or SVG|
|Convert AcroForms and XFA to HTML5|
|Java PDF SDK for working with PDF files|