DeeMoMo
DeeMoMo

Reputation: 35

Save JTextField inputs to text file

I have a form created for a users information. I need the data that is entered into the JTextFields to save to a text file. I have this action listener that builds the GUI when a button is pressed. Need help saving the data...

        static class Register implements ActionListener {

        public void actionPerformed (ActionEvent e){
            //Creates new JPanel 
            JFrame rFrame = new JFrame ("Register, Please Enter Your Information.");
            rFrame.setVisible(true);
            rFrame.setSize(800,800);
            JPanel rPanel = new JPanel(new GridLayout(0,2));
            rFrame.add(rPanel);

            //Creates register form
            JLabel Rfirstname = new JLabel("Firstname: "); rPanel.add(Rfirstname);
            JTextField firstname = new JTextField(40); rPanel.add(firstname);
            JLabel Rsurname = new JLabel("Surname: "); rPanel.add(Rsurname);
            JTextField surname = new JTextField(40); rPanel.add(surname);
            JLabel Rdob = new JLabel("D.O.B: "); rPanel.add(Rdob);
            JTextField dob = new JTextField(40); rPanel.add(dob);
            JLabel Raddress = new JLabel("Address: "); rPanel.add(Raddress);
            JTextField address = new JTextField(40); rPanel.add(address);
            JLabel Rpostcode = new JLabel("Post Code: "); rPanel.add(Rpostcode);
            JTextField postcode = new JTextField(40); rPanel.add(postcode);
            JLabel Rallergy = new JLabel("Allergy Info: "); rPanel.add(Rallergy);
            JTextField allergy = new JTextField(40); rPanel.add(allergy);
            JLabel Rcontact = new JLabel("Contact Details: "); rPanel.add(Rcontact);
            JTextField contact = new JTextField(40); rPanel.add(contact);

    }

Upvotes: 1

Views: 3778

Answers (1)

Thomas Böhm
Thomas Böhm

Reputation: 1486

I would write Code like that (in the function where you define your textfields, in your case in your method you showed in your question):

JTextField firstName=new JTextField();
    JButton but=new JButton("Save");
    but.addActionListener(e1->{
        try{
            BufferedWriter bw = new BufferedWriter(new FileWriter("asdf.txt"));
            bw.write(firstName.getText());
            bw.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    });

In this example, i simply write the Text of firstName. If you want to write all fields, you have to concat them (or something like that. Furthermore, you have to modify your path (If you use Windows, you also have to use / instead of \ for your path).

Upvotes: 5

Related Questions