save selected checkbox and radio button in notepad - java

I need to save information for my final project and need one little thing to complete it.
My Question is: How do I save a selected checkbox or radio button in notepad?
I know how to save any string-based information, but I don't know how to save the selected checkbox/radio button to my notepad - so, as I open it back and it will select it automatically. I tried if(chkE.isSelected() == true), but I don't know what to write to make it save into my notepad.
Thank you in advance!
Here is my code:
try {
JFileChooser flcFile = new JFileChooser("c:/");
int rep = flcFile.showSaveDialog(this);
File filesave = flcFile.getSelectedFile();
if (rep == JFileChooser.APPROVE_OPTION) {
try(FileWriter writer = new FileWriter(filesave)) {
//if(chkE.isSelected() == true){
//do stuff
//}
writer.write(String.valueOf(txtNom1.getText()));
writer.write("\r\n");
writer.write(String.valueOf(txtPre1.getText()));
writer.write("\r\n");
writer.write(String.valueOf(optoui.getText()));
writer.write("\r\n");
writer.write(String.valueOf(optoui.getText()));
writer.write("\r\n");
writer.write(String.valueOf(optnon.getText()));
writer.write("\r\n");
writer.write(String.valueOf(chkanimaux.getText()));
writer.write("\r\n");
writer.write(String.valueOf(chkChauffer.getText()));
writer.write("\r\n");
writer.write(String.valueOf(chkE.getText()));
writer.write("\r\n");
writer.write(String.valueOf(txttel.getText()));
writer.write("\r\n");
writer.close();
}
}
} catch(IOException err1) {
}
English isn't my native language.

It is hard to tell what you really want to do from your question. As I understand it, you have a dialog with different input elements that you want to save and then reload.
Since the value of a checkbox is a boolean value, just store the String representation of that value like this:
writer.write(String.valueOf(chkE.isSelected()));
When reading back, you convert the text by using
chkE.setSelected(Boolean.valueOf(text));
However, you should add some error handling code.

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/

How to load content of a text file and display it using ListView?

[I'm quite new with Android programming so please excuse me for my nooby questions]
I'm developing a dictionary app. One of this app's feature is the Favourite button which allows user to save favourite words (short-click) and view the list of favourite words (long-click).
So far, I have succeeded in saving words into a text file (myfav.txt). The format of the content of the text file is as below (each item on a line):
A
B
C
...
Z
However, I have problem in loading and viewing this file inside my app. I'm thinking of using ListView to display the content of "myfav.txt" but I don't really know what to do. I have consulted the Qs & As from other similar posts here but found myself more confused as a result.
Therefore, my questions are:
How can I load content of "myfav.txt" and display it using ListView? Could you please give detailed instructions as for beginners?
Are there any better ways to do view the content of "myfav.txt" other than ListView?
Here is my code:
//Reading lines from myfav.txt
btnAddFavourite.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
File sdcard = Environment.getExternalStorageDirectory();
setContentView(R.layout.text_view);
//trying opening the myfav.txt
try{
File f = new File(sdcard,"myfolder/myfav.txt");
InputStream fileIS = new FileInputStream(f);
BufferedReader buf = new BufferedReader(new InputStreamReader(fileIS));
String readString = new String();
while((readString = buf.readLine())!= null){
Log.d("Content: ", readString);
//How to code to load/view the content of "myfav.txt"
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return false;
}
});
Thank you very much indeed.
Hi you can find useful example here.
I do not think it's a good idea to use ListView for it. You'll need to provide ListAdapter if you choose this way.
I'd recommend using TextView (if you don't need to edit your text) or EdiText (if you do)
Using a file to save such information is not too sophisticated. I think you should look into tutorials about using SQLite, so you can store the words in a databse, and use cursors to view them in ListViews. You could use a separate boolean coloumn in you schema to mark favourited words that way for example.
Anyways, if you want to stick with files, one solution would be:
Read the contents of the file into a String array. You can use e.g. the Scanner class to easily read in lines from the file, and store them as separate strings in this array.
Construct a simple ArrayAdapter adapter class using this array.
Assign this adapter to a ListView.
Profit.
I am using following for writing to file -
FileOutputStream fout = null;
try {
fout = openFileOutput(fileName, MODE_PRIVATE);
ObjectOutputStream oos = new ObjectOutputStream(fout);
oos.writeObject(wordList); //writing arraylist<T>
oos.flush();
} catch(IOException e)
{
e.printStackTrace();
}
For reading -
fin = openFileInput(fileName);
ObjectInputStream ois = new ObjectInputStream(fin);
list =(ArrayList<T>)ois.readObject(); //reading in arraylist directly

Refreshing JTextArea with new values

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.

Can a user-chosen image be inserted directly into a JEditorPane?

What I am trying to do is open up a JFilechooser that filters jpeg,gif and png images, then gets the user's selection and inserts it into the JEditorPane. Can this be done? or am i attempting something impossible? Here is a sample of my program.(insert is a JMenuItem and mainText is a JEditorPane)
insert.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
JFileChooser imageChooser = new JFileChooser();
imageChooser.setFileFilter(new FileNameExtensionFilter("Image Format","jpg","jpeg","gif","png"));
int choice = imageChooser.showOpenDialog(mainText);
if (choice == JFileChooser.APPROVE_OPTION) {
mainText.add(imageChooser.getSelectedFile());
}
}
});
What i tried to do is use the add method, i know it's wrong but just to give you an idea of what i'm trying to do.
Before you complain, i'm sorry about the code formatting, i don't really know all the conventions of what is considered good or bad style.
Thank you very much.
This is the part of the code i use to save the html file.
else if (e.getSource() == save) {
JFileChooser saver = new JFileChooser();
saver.setFileFilter(new FileNameExtensionFilter(".html (webpage format)" , "html"));
int option = saver.showSaveDialog(this);
if (option == JFileChooser.APPROVE_OPTION) {
try {
BufferedWriter out = new BufferedWriter(new FileWriter(saver.getSelectedFile().getPath()));
out.write(mainText.getText());
out.close();
} catch (Exception exception) {
System.out.println(exception.getMessage());
}
}
}
Its easier to just use a JTextPane. Then you can use insertIcon(...) anywhere in the text.
Edit:
I have never had much luck trying to manipulate HTML but I've used code like the following before:
HTMLEditorKit editorKit = (HTMLEditorKit)textPane.getEditorKit();
text = "hyperlink";
editorKit.insertHTML(doc, textPane.getCaretPosition(), text, 0, 0, HTML.Tag.A);
So presumably the code would be similiar for the IMG tag.
This should do it:
mainText.setContentType("text/html");
String image = String.format("<img src=\"%s\">", imageChooser.getSelectedFile());
mainText.setText(image);

Categories