Copy text to clipboard from a JTextfield with press of a button

copy-paste, java, jtextfield, swing

Solution

You can copy the text with the following code

StringSelection stringSelection = new StringSelection (txtField.getText());
Clipboard clpbrd = Toolkit.getDefaultToolkit ().getSystemClipboard ();
clpbrd.setContents (stringSelection, null);

The text will be copied to your clip board and then it can be pasted anywhere. In any editor.

Read more about Clipboard, Toolkit, StringSelection

I Hope you know how to import packages/classes in Java

Hint

As you want to copy text in a Text Field, you can add the above code in `actionPerformed()` method of you ActionListener.

Problem

After working on a `GUI` that prints your Text backwards `(Hello = olleH)`, Now I want to create a little Button that lets you `copy` the Outcome in a way you can paste it anywhere else (example in any Editor). I am using a `JTextfield` called `jtxtoutcome`. I don't know what else I could say, I guess this is pretty accurate. This is how I use to change the outcome Textfield.: ``` jtxtoutcome.setText(backwards); ```

Original source

Related problems