Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
like image 320
fihdi Avatar asked Jul 11 '14 16:07

fihdi


1 Answers

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.

like image 162
gprathour Avatar answered Oct 27 '22 07:10

gprathour