Home > Back-end >  How do I add user input from JTextfield to Text file
How do I add user input from JTextfield to Text file

Time:05-15

I've been trying to create a simple register form using GUI and I am having a hard time in saving the user inputs from JTextfield to a txt file. So far this is what I have come up with:

package com.main;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;

public class RegisterScreen extends JFrame implements ActionListener{

JLabel lblCreateUser, lblCreatePassword; 
JTextField txtNewUsername, txtNewPassword;

JButton btnCreateAccount;
public RegisterScreen(){
    super("Create new User");
    setLayout(null);

    lblCreateUser = new JLabel("Please enter your Email Address");
    lblCreatePassword = new JLabel("Please enter your Password");
    txtNewUsername = new JTextField("Username");
    txtNewPassword = new JTextField("Password");
    btnCreateAccount = new JButton("Create account");
 

    lblCreateUser.setBounds(100,50, 250,40);
    lblCreatePassword.setBounds(50, 150, 300, 40);
    txtNewUsername.setBounds(50, 200, 300,  40);
    txtNewPassword.setBounds(125, 250, 150, 40);
    btnCreateAccount.setBounds(125, 350,150, 12);

    btnCreateAccount.addActionListener(this);

    add(lblCreateUser);
    add(txtNewUsername);
    add(lblCreatePassword);
    add(txtNewPassword);
    add(btnCreateAccount);

    addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent exit){
            System.exit(0);
        }
    });
    setSize(400,600);
    setVisible(true);
    setResizable(false);

}
public static void main (String []args){
    RegisterScreen register = new RegisterScreen();
}
public void actionPerformed(ActionEvent e) {
    try{
        BufferedWriter addUser = new BufferedWriter(new FileWriter("Usernames.txt"));
        BufferedWriter addPassword = new BufferedWriter(new FileWriter("Passwords.txt"));

        if(e.getSource() == btnCreateAccount){
          
           addUser.write(txtNewUsername.getText()  "\n");
           addPassword.write(txtNewPassword.getText() "\n");

           addUser.close();
           addPassword.close();

           JOptionPane.showMessageDialog(null, "Account Successfully Created", "Success",1);
        }
    }
    catch(IOException err){
        System.err.println("File not Found.");
    }
   
    
}

}

In this program, the username and password will be stored separately to their respective text file. The problem is that whenever I tried clicking the create account button, instead of adding the user inputs to another line, it completely replaced the whole contents of the file itself to the user input. Any help is much appreciated.

CodePudding user response:

Works fine for me...

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.EventQueue;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

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

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame();
                frame.add(new TestPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class TestPane extends JPanel implements ActionListener {

        private JTextField txtNewUsername;
        private JPasswordField txtPassword;
        private JButton btnCreateAccount;

        public TestPane() {
            setLayout(new GridBagLayout());
            GridBagConstraints gbc = new GridBagConstraints();
            gbc.gridwidth = GridBagConstraints.REMAINDER;

            txtNewUsername = new JTextField(10);
            txtPassword = new JPasswordField(10);
            btnCreateAccount = new JButton("Create");

            add(txtNewUsername, gbc);
            add(txtPassword, gbc);
            add(btnCreateAccount, gbc);

            btnCreateAccount.addActionListener(this);
        }

        public void actionPerformed(ActionEvent e) {
            File user = new File("Usernames.txt");
            File pass = new File("Passwords.txt");

            if (e.getSource() == btnCreateAccount) {
                try (BufferedWriter addUser = new BufferedWriter(new FileWriter(user, true)); BufferedWriter addPass = new BufferedWriter(new FileWriter(pass, true))) {
                    addUser.write(txtNewUsername.getText());
                    addUser.newLine();
                    addPass.write(txtPassword.getText());
                    addPass.newLine();
                    JOptionPane.showMessageDialog(null, "Account Successfully Created", "Success", JOptionPane.INFORMATION_MESSAGE);
                } catch (IOException exp) {
                    JOptionPane.showMessageDialog(this, "Account creation failed", "Error", JOptionPane.ERROR_MESSAGE);
                }
            }
        }

    }
}

You might also consider having a look at The try-with-resources Statement

CodePudding user response:

To hold user input, you can you any number of Objects. I will use a StringBuilder here:

StringBuilder userInput = new StringBuilder();

Then to read the input, call the name with this method:

userInput.append(fieldName.getText()).append("\n");

After that, you need to write it to a file with any other handful of Objects. I will use the FileWriter here:

FileWriter fileWriter = new FileWriter("filename.txt");

Then call the following:

fileWriter.write(userInput.toString());

And ultimately when you are done writing:

fileWriter.close();

More information

.append(String s) is used to append the specified string with this string. The append() method is overloaded like append(char), append(boolean), append(int), append(float), append(double) etc.

FileWriter(String file) creates a new file; it gets file name in string. void write(String text) is used to write the string into FileWriter. And void close() is used to close the FileWriter.

  • Related