简体   繁体   中英

Swing Code to copy data from 2 text area to clipboard

[![enter image description here][1]][1]I am new to Java Swing. I have a create a GUI layout will 2 text areas and a button "copy to clipboard". 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.

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. 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 :-) . Just create JSON content like this:

[
    {
       "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 . 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:

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

Or you could use a 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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