简体   繁体   English

只需按一下按钮,即可从JTextfield将文本复制到剪贴板

[英]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). 在处理向后打印文本的GUI (Hello = olleH) ,现在我想创建一个小按钮,让您以一种可以将其粘贴到任何其他位置的方式copy结果(例如在任何编辑器中)。 I am using a JTextfield called jtxtoutcome . 我使用的是JTextfield称为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.: 这是我用来改变结果的方法Textfield:

jtxtoutcome.setText(backwards);

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 阅读有关ClipboardToolkitStringSelection的更多信息

I Hope you know how to import packages/classes in Java 我希望你知道如何用Java导入包/类

Hint 暗示

As you want to copy text in a Text Field, you can add the above code in actionPerformed() method of you ActionListener . 由于您要在文本字段中复制文本,因此可以在ActionListener的 actionPerformed()方法中添加上述代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM