简体   繁体   English

Swing代码将数据从2个文本区域复制到剪贴板

[英]Swing Code to copy data from 2 text area to clipboard

[![enter image description here][1]][1]I am new to Java Swing. [![在此处输入图像描述] [1]] [1]我是Java Swing的新手。 I have a create a GUI layout will 2 text areas and a button "copy to clipboard". 我创建了一个GUI布局,将2个文本区域和一个按钮“复制到剪贴板”。 I have a code that will copy the contents of first text area to clipboard, but not sure how to add the content in second text area and the labels corresponding to jtext area. 我有一个代码,它将第一个文本区域的内容复制到剪贴板,但是不确定如何在第二个文本区域中添加内容以及与jtext区域相对应的标签。

String get= hActionText.getText();
   StringSelection selec= new StringSelection(get);
   Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
   clipboard.setContents(selec, selec);

If I understood what are you trying, you are trying to put the values of both of your fields on the clipboard, and than read them and populate the fields again. 如果我了解您要尝试的内容,那么您将尝试将两个字段的值都放在剪贴板上,然后读取它们并再次填充字段。

The clipboard is way too simple for that, it can only hold one String basically. 剪贴板太简单了,它基本上只能容纳一个String。 What I propose is to create a structure you will put on the clipboard, and which structure is better for describing data as a String than JSON :-) . 我建议的是创建一个将放置在剪贴板上的结构,该结构比JSON :-)更适合将数据描述为String。 Just create JSON content like this: 只需像这样创建JSON内容:

[
    {
       "label":"field1",
       "content":"contentFromField1"
    },
    {
       "label":"field2",
       "content":"contentFromField2"
    }
]

And put it on the clipboard. 并将其放在剪贴板上。 Of course, you always have to check after reading the clipboard is the content actually deserializable. 当然,在阅读剪贴板后,您始终必须检查一下实际可反序列化的内容。

For creating content like this you can use a Java library like json-simple . 为了创建这样的内容,您可以使用json-simple之类的Java库。 A simple example with the content like above: 一个简单的示例,其内容如上:

JSONObject obj1 = new JSONObject();
obj1.put("label", "field1");
obj1.put("content", "contentFromField1);

JSONObject obj2 = new JSONObject();
obj2.put("label", "field2");
obj2.put("content", "contentFromField2);

JSONArray list = new JSONArray();
list.add(obj1);
list.add(obj2);

please help me with concatenation? 请帮助我进行串联吗?

This is basic java that I'm sure you use all the time: 这是我确定您一直使用的基本Java:

String textForClipboard = label1.getText() + ":" + label2.getText();

Or you could use a StringBuilder : 或者您可以使用StringBuilder

StringBuilder sb = new StringBuilder();
sb.append( labe1.getText() );
sb.append( ":" );
sb.append( label2.getText() );

Then when you get the data from the clipboard you need to parse it. 然后,当您从剪贴板中获取数据时,您需要对其进行解析。 You could use the String.split(...) method. 您可以使用String.split(...)方法。

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

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