5

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);
Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
fihdi
  • 145
  • 1
  • 1
  • 12
  • @DavidPostill how to create a Button that lets you copy the text from the JTextfield – fihdi Jul 11 '14 at 16:39
  • 1
    duplicate of http://stackoverflow.com/questions/6710350/copying-text-to-the-clipboard-using-java – Simon Meyer Jul 11 '14 at 16:40
  • 1
    The button is just like any other button. You need a click listener at which time you grab the text and put it in the clipboard. [Look here.](http://www.javapractices.com/topic/TopicAction.do?Id=82) – ChiefTwoPencils Jul 11 '14 at 16:41
  • As you are new to Stackoverflow, I would like to tell you if you find a solution to your problem then you should accept that answer, so that others having same problem could come to know about solutions. To accept the answer, you should click on the Tick sign you will see below the up down arrows on the left side. You can accept only one answer per question. – gprathour Jul 11 '14 at 18:26

1 Answers1

8

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.

gprathour
  • 14,813
  • 5
  • 66
  • 90