-1

I have one project that I want to get input from jframe. I have to input 3 people data in only one time when code was running and write that data into file name person.txt.Those data have Name Nickname Age and when i compile my code, It dosn't work and I just only write one data in person.txt file. Help me please? I can't get those in my project. what should i do ?

 public class JavaGui {
  public String data = "";
  JFrame f;
  JLabel l1, l2, l3;
  JTextField tf1, tf2, tf3;
  JButton b;
  JavaGui() {

   FileWriter fw = null;
   try {
    fw = new FileWriter("person.txt");
   } catch (IOException ex) {
    Logger.getLogger(JavaGui.class.getName()).log(Level.SEVERE, null, ex);
   }

   PrintWriter pw = new PrintWriter(fw);


   f = new JFrame("Java GUI");
   l1 = new JLabel("Name");
   l1.setBounds(20, 50, 80, 30);
   tf1 = new JTextField();
   tf1.setBounds(100, 50, 200, 30);

   l2 = new JLabel("Nickname");
   l2.setBounds(20, 100, 80, 30);
   tf2 = new JTextField();
   tf2.setBounds(100, 100, 200, 30);

   l3 = new JLabel("Age");
   l3.setBounds(20, 150, 80, 30);
   tf3 = new JTextField();
   tf3.setBounds(100, 150, 200, 30);

   b = new JButton("Save");
   b.setBounds(100, 200, 70, 30);

   f.add(l1);
   f.add(tf1);
   f.add(l2);
   f.add(tf2);
   f.add(l3);
   f.add(tf3);
   f.add(b);
   f.setSize(350, 350);
   f.setLayout(null);
   f.setLocationRelativeTo(null);
   f.setResizable(false);
   f.setVisible(true);
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

   for (int i = 0; i < 3; i++) {
    b.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent e) {

      String name = "";
      String nickname = "";
      String ageS = "";
      int age = 0;
      try {
       name = "Name : " + tf1.getText();
       nickname = "Nickname : " + tf2.getText();
       age = Integer.parseInt(tf3.getText());

       if (age > 0 && age < 100) {
        ageS = "Age : " + age;
       } else {
        JOptionPane.showMessageDialog(null, "Please Enter Age field by Positive number Or Less than 100");
       }
      } catch (NumberFormatException ex) {
       JOptionPane.showMessageDialog(null, "Please enter Age field by number type");

      }

      data += name + " " + nickname + " " + ageS;

      pw.println(data);
      pw.close();

     }

    });
   }

  }

  public static void main(String[] args) {
   new JavaGui();
  }

 }
Raju Sharma
  • 2,496
  • 3
  • 23
  • 41
BLoveCoding
  • 11
  • 2
  • 4
  • I got information like this `Name : MyName Nickname : MyNickname Age : 14` It seems to work as I expect. Having said that, safest to change `pw.println(data); pw.close();` to `pw.println(data); pw.flush(); pw.close();`. General advice: 1) Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with .. – Andrew Thompson Nov 17 '17 at 14:11
  • .. layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). 2) See [Detection/fix for the hanging close bracket of a code block](http://meta.stackexchange.com/q/251795/155831) for a problem I could no longer be bothered fixing. – Andrew Thompson Nov 17 '17 at 14:11
  • I want to add more than one person's data in this code sir. help me please? – BLoveCoding Nov 17 '17 at 14:34
  • Try FileWriter not PrintWritter – Marios Nikolaou Nov 17 '17 at 15:28

2 Answers2

0

I want to add more than one person's data in

You want to write to the file using a FileWriter (not a PrintWriter).

Then when you create the FileWriter you can "append" data to the file. Read the FileWriter API for the appropriate constructor to use.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • Thanks, but i want to get input 3 times and then i want to write those previous input into file .txt . Help me – BLoveCoding Nov 17 '17 at 16:21
  • I did help you. I don't understand the problem. If you can write one person to a file why can't you write a second person?. The code will be the same except the data is different or where you get the data is different. . – camickr Nov 17 '17 at 19:32
  • The problem is how to get input more than one person. When I use loop in this code, I get the same person data . I need different people data.In this case I can input how many people that I want and all of those data will save to person.txt file – BLoveCoding Nov 17 '17 at 19:55
  • Well you need to design your application to accept data from more than one person So first of all get rid of the loop. It is not needed and should not be used in an event driven GUI. So you have text field where the user can enter data. Then you have a "Save" button. When the user clicks on the save button, you get the data from the text fields and write it to a file. Then you clear the data from the text file so the user can enter more data. – camickr Nov 17 '17 at 20:24
  • So is it not necessary to use loop bro? – BLoveCoding Nov 18 '17 at 05:34
0

Tested and working fine.I have added next button so each time you append new data in StringBuilder and at the end you can save that persons.You can remove the counter(i have added counter to add only 3 persons) and make it without limit.

import javax.swing.*;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class JavaGui {
JFrame f;
JLabel l1, l2, l3;
JTextField tf1, tf2, tf3;
JButton b,next;
int counter;

StringBuilder data = new StringBuilder();
JavaGui() {}

public static void main(String[] args) {

    FileWriter fw = null;
    try{
        fw = new FileWriter("person.txt");
        PrintWriter pw = new PrintWriter(fw);
        new JavaGui().go(pw);

       }catch (IOException ex) {
        Logger.getLogger(JavaGui.class.getName()).log(Level.SEVERE, null, ex);
    }


}

public void go(PrintWriter pw) {

    f = new JFrame("Java GUI");
    l1 = new JLabel("Name");
    l1.setBounds(20, 50, 80, 30);
    tf1 = new JTextField();
    tf1.setBounds(100, 50, 200, 30);

    l2 = new JLabel("Nickname");
    l2.setBounds(20, 100, 80, 30);
    tf2 = new JTextField();
    tf2.setBounds(100, 100, 200, 30);

    l3 = new JLabel("Age");
    l3.setBounds(20, 150, 80, 30);
    tf3 = new JTextField();
    tf3.setBounds(100, 150, 200, 30);

    next = new JButton("Next");
    next.setBounds(100, 200, 70, 30);

    b = new JButton("Save");
    b.setBounds(180, 200, 70, 30);

    f.add(l1);f.add(tf1);
    f.add(l2);f.add(tf2);
    f.add(l3);f.add(tf3);
    f.add(next);
    f.add(b);
    f.setSize(350, 350);
    f.setLayout(null);
    f.setLocationRelativeTo(null);
    f.setResizable(false);
    f.setVisible(true);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    next.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent e) {
            String name = "";
            String nickname = "";
            String ageS = "";
            int age = 0;

              try{    
                name = "Name : " + tf1.getText();
                nickname = "Nickname : " + tf2.getText();
                age =Integer.parseInt(tf3.getText());

                if(age > 0 && age < 100) {
                    ageS = "Age : " + age;
                }else{
                    JOptionPane.showMessageDialog(null, "Please Enter Age field by Positive number Or Less than 100");
                }
               }catch(NumberFormatException ex){
                JOptionPane.showMessageDialog(null, "Please enter Age field by number type");
               }

               data.append(name + " " + nickname + " " + ageS);
               data.append(System.getProperty("line.separator"));

               counter++;

               tf1.setText("");
               tf2.setText("");
               tf3.setText("");

               if(counter > 2)
                   next.setEnabled(false);
        }

    });

    b.addActionListener(new ActionListener(){
        public void actionPerformed(ActionEvent e){

            pw.print(data.toString());
            pw.close();

        } 

    });
 }

}
Marios Nikolaou
  • 1,326
  • 1
  • 13
  • 24
  • Did I used for loop in this code correctly? i want to get input 3 times and then i want to write those previous input into file .txt . Help me – BLoveCoding Nov 17 '17 at 16:19
  • So you want to write the same data 3 times in file? – Marios Nikolaou Nov 17 '17 at 19:13
  • No, bro sorry if I ask you unclearly . I want to get different people data in only one time when code was running . So I chose for loop for doing this but it isn't my expect. I can write just only one time for one person that there are saving to person.txt file. The for loop was doing the same person . Help me for the best way bro? – BLoveCoding Nov 17 '17 at 20:04
  • The OP is using a `FileWriter`, the wrap it in the `PrintWriter` - the resource management is also wrong, as the writer should be opened in the `actionPerformed` method and closed within in `try-finally` or `try-with-resources` block – MadProgrammer Nov 17 '17 at 21:06