Swing Code to copy data from 2 text area to clipboard - java

[![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.

Related

Add byte array inside a json object using java

I have below situation. It needs to be implemented in Java.
Take input from a text file, convert the content into a byte array.
Use the above byte array as a part of a JSON object , create a .json file
For point1, i have done something like this.
InputStream is = new ClassPathresource("file.txt").getInputStream();
byte[] ip = IOUtils.toByteArray(is);
For point2, my Json file (containing json object), should look like below.
{
"name": "xyz",
"address: "address here",
"ipdata": ""
}
The ipdata should contain the byte array created in step 1.
How can i create a json object with the byte array created in step 1 as a part of it ? And then write the entire content to a separate .json file ?
Also is the byte array conversion done in step1 an optimum way, or do we need to use any other API(may be to take care of encoding)?Please suggest.
Any help is appreciated. Thanks in advance.
You can simply convert the byte array ip using ip.toString()
Or if you know the encoding you can use ipString = new String(ip, "UTF8")
And then take that string to add to your json object.
Since you are reading a JSON string from file and want to write it back to a new json file you dont need the JSON Object conversion in-between. Just convert the byte[] to String as
String ips = new String(ip);
Now create a JSON Object with the data you want to write to the new file. And then you can write the data to file using FileWriter. PFB the code-
JSONObject obj = new JSONObject();
obj.put("name", "xyz");
obj.put("address", "address here");
obj.put("ipdata", ips);
try(FileWriter fileWriter =
new FileWriter("newFileName.json") ){
fileWriter.write(obj.toString());
}

JAVA POI DOCX replace text in paragraph

Hi i m trying to replace some text in a docx file, but i got problemes with text to be replaced that can be on multiple runs. So i tried this : but it erase everything in the document :/
private void replaceText(XWPFParagraph p, String target, String replacement) {
if (p.getRuns() != null) {
String paragraph = p.getText();
for (int i = 0; i < p.getRuns().size(); i++) {
p.removeRun(i);
}
paragraph = paragraph.replace(target, replacement);
XWPFRun r = new XWPFRun(CTR.Factory.newInstance(), p);
r.setText(paragraph, 0);
}
}
It will surely erase everything because you are removing all the runs in the paragraph. Point to understand here is that the text in the paragraph is stored inside the runs. What getText() does is it returns all the text in all the runs of the paragraph.
Removing all runs and adding just one new run will surely disrupt the font and alignment of the text
You are removing all the runs and then adding one run with the replaced text.
I believe this is not what you wish to achieve.
Just loop over the runs and replace the text inside them.
For one of my projects I chose a different route, I work on the underlying XML data and do a search/replace there which usually works quite nicely.
See https://github.com/centic9/poi-mail-merge for the details, but basically I fetch the CTBody low-level item via
CTBody body = doc.getDocument().getBody();
And then read the full XML body text
// read the current full Body text
String srcString = body.xmlText();
then do the replacements.
Finally I create a new CTBody item with the new contents via
CTBody makeBody = CTBody.Factory.parse(resultStr);
See https://github.com/centic9/poi-mail-merge/blob/master/src/main/java/org/dstadler/poi/mailmerge/MailMerge.java#L81 for the full code-details as there are a few more things that are handled to make it work nicely.

How to display multiple Hyperlinks in Java

I want to display multiple Hyperlinks using JEditorPane.To be more specific i have a HashSet named urlLinks:
static Set<String> urlList = new HashSet<>();
and inside it I store urls like
www.google.com
www.facebook.com
etc.
As i said i am using the JEditorPane and I set it like this:
static final JEditorPane ResultsArea = new JEditorPane();
ResultsArea.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
ResultsArea.setEditable(false);
At some point I want to display on the JEditorPane all these links as Hyperlinks
so I do this:
for(String s : urlList)
{
s=(""+s+""+"\n");
ResultsArea.setText(ResultsArea.getText()+s+"\n");
}
but it doesn't display anything.
When i try to change it like this
ResultsArea.setText(s);
it displays me only one of them.However I want to display all of them one after the other
like
www.example.com
www.stackoverflow.com
etc.
Does anyone know how to do that?
Use a StringBuilder to build the list of URLs first.
StringBuilder sb = new StringBuilder();
for (String s : urlList) {
sb.append("").append(s).append("\n");
}
ResultsArea.setText(sb.toString()); // then set the complete URL list once

Read the five score in a textfile then print them back with the new score added to the list - ANDROID

In my program when the player submits a score it gets added to a local text file called localHighScores. This is list of the top five score the player has achieved while on that specific device.
I wasn't sure how to write to a new line using FileOutputStream (if you know please share), so instead I've inputted a space in between each score. Therefore what I am trying to do is when the player clicks submit the program will open the file and read any current data is saved. It will save it to an String Array, each element being one of the five score in the text file and when it hits a 'space' in the fie it will add the score just read to the write array element
The code I currently have is as follows:
String space = " ";
String currentScoreSaved;
String[] score = new String[5];
int i = 0;
try
{
BufferedReader inputReader = new BufferedReader(new InputStreamReader(openFileInput("localHighScore.txt")));
String inputString;StringBuffer stringBuffer = new StringBuffer();
while ((inputString = inputReader.readLine()) != null && i < 6)
{
if((inputString = inputReader.readLine()) != space)
{
stringBuffer.append(inputString + "\n");
i++;
score[i] = stringBuffer.toString();
}
}
currentScoreSaved = stringBuffer.toString();
FileOutputStream fos = openFileOutput("localHighScore.txt", Context.MODE_PRIVATE);
while (i < 6)
{
i++;
fos.write(score[i].getBytes());
fos.write(space.getBytes());
}
fos.write(localHighScore.getBytes());
//fos.newLine(); //I thought this was how you did a new line but sadly I was mistaken
fos.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Now you will notice this doesn't re arrange the score if a new highscore is achieved. That I am planning on doing next. For the moment I am just trying to get the program to do the main thing which is read in the current data, stick it in an Array then print it back to that file along with the new score
Any Ideas how this might work, as currently it's printing out nothing even when I had score in the textfile before hand
I'm only a first year student in Java programming and I am a new user here at stackoverflow.com, so pardon me if coding for android has some special rules I don't know about, which prevents this simple and humble example from working. But here is how I would read from a file in the simplest of ways.
File tempFile = new File("<SubdirectoryIfAny/name_of_file.txt");
Scanner readFile = new Scanner( tempFile );
// Assuming that you can structure the file as you please with fx each bit of info
// on a new line.
int counter = 0;
while ( readFile.hasNextLine() ) {
score[counter] = readFile.nextLine();
counter++;
}
As for the writing back to the file? Put it in an entirely different method and simply make a simplified toString-like method, that prints out all the values the exact way you want them in the file, then create a "loadToFile" like method and use the to string method to print back into the file with a printstream, something like below.
File tempFile = new File("<SubdirectoryIfAny/name_of_file.txt");
PrintStream write = new PrintStream(tempFile);
// specify code for your particular program so that the toString method gets the
// info from the string array or something like that.
write.print( <objectName/this>.toStringLikeMethod() );
// remember the /n /n in the toStringLikeMethod so it prints properly in the file.
Again if this is something you already know, which is just not possible in this context please ignore me, but if not I hope it was useful. As for the exceptions, you can figure that you yourself. ;)
Since you are a beginner, and I assume you are trying to get things off the ground as quickly as possible, I'd recommend using SharedPreferences. Basically it is just a huge persistent map for you to use! Having said that... you should really learn about all the ways of storage in Android, so check out this document:
http://developer.android.com/guide/topics/data/data-storage.html
The Android docs are awesome! FYI SharedPreferences may not be the best and awesomest way to do this... but I'm all for quick prototyping as a learner. If you want, write a wrapper class around SharedPreferences.

Textscreen in Codename One, how to read text file?

I want to add a help screen to my Codename One App.
As the text is longer as other strings, I would like put it in a separate file and add it to the app-package.
How do I do this? Where do I put the text file, and how can I easily read it in one go into a string?
(I already know how to put the string into a text area inside a form)
In the Codename One Designer go to the data section and add a file.
You can just add the text there and fetch it using myResFile.getData("name");.
You can also store the file within the src directory and get it using Display.getInstance().getResourceAsStream("/filename.txt");
I prefer to have the text file in the filesystem instead of the resource editor, because I can just edit the text with the IDE. The method getResourceAsStream is the first part of the solution. The second part is to load the text in one go. There was no support for this in J2ME, you needed to read, handle buffers etc. yourself. Fortunately there is a utility method in codename one. So my working method now looks like this:
final String HelpTextFile = "/helptext.txt";
...
InputStream in = Display.getInstance().getResourceAsStream(
Form.class, HelpTextFile);
if (in != null){
try {
text = com.codename1.io.Util.readToString(in);
in.close();
} catch (IOException ex) {
System.out.println(ex);
text = "Read Error";
}
}
The following code worked for me.
//Gets a file system storage instance
FileSystemStorage inst = FileSystemStorage.getInstance();
//Gets CN1 home`
final String homePath = inst.getAppHomePath();
final char sep = inst.getFileSystemSeparator();
// Getting input stream of the file
InputStream is = inst.openInputStream(homePath + sep + "MyText.txt");
// CN1 Util class, readInputStream() returns byte array
byte[] b = Util.readInputStream(is);
String myString = new String(b);

Categories