Refreshing JTextArea with new values - java

I am new to java.
I have a project from college where I have to make entries to txt file through 2 JTextField boxes and 1 JButton (save) which will display the entries in JTextArea. I am able to make entries in txt file successfully. But how to refresh JTextArea at run-time to display the new entries I recently made?
Thanks for helps:
below is my code:
try {
//use buffering, reading one line at a time
//FileReader always assumes default encoding is OK!
BufferedReader input = new BufferedReader(new FileReader("RokFile.txt"));
try {
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
jTextArea1.append(line+"\n");
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
Let me know if its correct?
Thanks

JTextArea.append ought to suffice. This method is thread-safe and will update the text area's content automatically.
This answer assumes that you already have the EventListeners configured.

You can use two methods,
If you want to display the content as soon as you write in jTextField(fairly attainable), you can do it this way, in the FocusLost event of jTextField, give something like jTextArea.setText(jTextField.getText())
Note, that this is fairly near to what you want.(also,NOT perfect code)
If you want to display the contents when you click save , the above code, jTextArea.setText(jTextField.getText()) may be given in the event handler of the save button.

Related

I am trying to advance to a new information each time someone signs up on my java application

So everytime someone clicks sign up on my program, I call a method that opens file and adds record.
This is to open the file:
try {
l = new Formatter("chineses.txt");
System.out.println("Did create");
} catch (Exception e){
System.out.println("Did not create");
}
public void addRecord(){ //This is how i add the record
l.format("%s", nameField.getText());
}
Everytime I put in a name in the name field and click sign up in my gui, it always replaces whatever is on the first line in the text file.
How can I make it go to the second line while retaining what is on the first line each time someone else puts their name and clicks sign up?
You just need to create the object of FileWriter and pass it to the Formatter. It will append your text in the File.
Try this code:
FileWriter writer = new FileWriter("chineses.txt",true);
l = new Formatter(writer);
public void addRecord(){ //This is how i add the record
l.format("%s\n", nameField.getText());
}

[JAVA]How to create a Ranking System then saving it to a .txt file?

So, I have a "Memory Game", you can input your name, choose the difficulty(4x4 or a 6x6 game) and then start the game.
When you click Start, a new Panel will pop up and the game will start.
The buttons will be randomized and for each mistake you make, you lose 2 points and for every right combination, you gain 10 points.
At the end or if you click on the Exit button, a message will pop up stating the Player's Name, how many tries he did(clicked 2 different buttons) and how many Points he has. Then the game ends and it doesn't save the Player's Score.
Now, my problem is, I don't know how to implement a Ranking System in my code. It would be something basic, like, a comparison between all the Scores and rearrange them to the one with the most points comes first and so on.
So from what I researched, I would need a Save method that whenever someone finishes a game it would save their scores in a .txt file and an Array method that would arrange the scores form Best to Worst.
Here's the whole code;
http://pastebin.com/6Wtiju7z
private void mostrarResumoJogo() {
resumoJogo = "Jogador: " + objJogadorJogada.getNome() + " " +
"Pontos: " + objJogadorJogada.getPontos() + " " +
"Quantidade de tentativas: " + qtdeTentativas;
JOptionPane.showMessageDialog( null, "" + resumoJogo, "Resumo do Jogo",
JOptionPane.INFORMATION_MESSAGE );
BufferedWriter writer = null;
try {
writer = new BufferedWriter( new FileWriter("Ranking.txt") );
writer.write(resumoJogo);
}
catch ( IOException e) { }
finally {
try {
if (writer != null)
writer.close( );
}
catch ( IOException e) { }
}
setVisible( false );
}
The problem is that the file is always overwritten with a new .txt
I already tried to create a type File attribute so that he doesn't always create another .txt but with no success.
It's the last thing that I need to do on this code, but I can't seem to figure it out, please, help.
The problem is that the file is always overwritten with a new .txt
Problem is here
writer = new BufferedWriter( new FileWriter( "Ranking.txt"));
Each time you invoke new FileWriter( "Ranking.txt") it creates new empty file. If you want to add more data to already existing file you need to open it in append mode via
writer = new BufferedWriter( new FileWriter( "Ranking.txt", true));
// add this part -^^^^
Probably this is what are you looking for
https://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html#FileWriter(java.lang.String,%20boolean)
Just specify APPEND parameter as true and your changes won't be overwritten
To make it not overwrite, but append instead pass append=true when calling the FileWriter constructor.
Instead of doing that though I would recommend just reading and writing the whole file every time. This is because the scores have to be sorted and rewritten to the file.
I would recommend using JAXB to create an XML file. Here is a tutorial for using JAXB to do this: http://www.mkyong.com/java/jaxb-hello-world-example/

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);

Java - Load file, replace string, save

I have a program that loads lines from a user file, then selects the last part of the String (which would be an int)
Here's the style it's saved in:
nameOfValue = 0
nameOfValue2 = 0
and so on. I have selected the value for sure - I debugged it by printing. I just can't seem to save it back in.
if(nameOfValue.equals(type)) {
System.out.println(nameOfValue+" equals "+type);
value.replace(value, Integer.toString(Integer.parseInt(value)+1));
}
How would I resave it? I've tried bufferedwriter but it just erases everything in the file.
My suggestion is, save all the contents of the original file (either in memory or in a temporary file; I'll do it in memory) and then write it again, including the modifications. I believe this would work:
public static void replaceSelected(File file, String type) throws IOException {
// we need to store all the lines
List<String> lines = new ArrayList<String>();
// first, read the file and store the changes
BufferedReader in = new BufferedReader(new FileReader(file));
String line = in.readLine();
while (line != null) {
if (line.startsWith(type)) {
String sValue = line.substring(line.indexOf('=')+1).trim();
int nValue = Integer.parseInt(sValue);
line = type + " = " + (nValue+1);
}
lines.add(line);
line = in.readLine();
}
in.close();
// now, write the file again with the changes
PrintWriter out = new PrintWriter(file);
for (String l : lines)
out.println(l);
out.close();
}
And you'd call the method like this, providing the File you want to modify and the name of the value you want to select:
replaceSelected(new File("test.txt"), "nameOfValue2");
I think most convenient way is:
Read text file line by line using BufferedReader
For each line find the int part using regular expression and replace
it with your new value.
Create a new file with the newly created text lines.
Delete source file and rename your new created file.
Please let me know if you need the Java program implemented above algorithm.
Hard to answer without the complete code...
Is value a string ? If so the replace will create a new string but you are not saving this string anywhere. Remember Strings in Java are immutable.
You say you use a BufferedWriter, did you flush and close it ? This is often a cause of values mysteriously disappearing when they should be there. This exactly why Java has a finally keyword.
Also difficult to answer without more details on your problem, what exactly are you trying to acheive ? There may be simpler ways to do this that are already there.

Categories