Search code examples
javaswingtext-fileswritefile

How to Clear variables from JTextFields without closing whole program?


I have created a text file in which to store some variables which are taken from text fields. But in order to submit new variables to this text file, I need to close my program and reopen it. The dispose(); command closes the JFrame taking me to my main menu but upon opening the menu again and submitting different values, the values from the previous time have been resubmitted. Is there a simple way to amend this?

Here is my write to .txt code:

public class writeto {

static String data = AddProperty.inputdata;
BufferedWriter out;

public writeto(){
        try{
            out = new BufferedWriter(new FileWriter("writeto.txt", true));

            out.write(data);

            out.newLine();

            out.close();

        }catch(IOException e){

            System.out.println("you have an error" + e);
        }
    }
}

and where the method is called in my addproperty class

        submitproperty.addActionListener(new ActionListener()
        {

        public void actionPerformed(ActionEvent e)
            {
              housenumber1 = houseNumber.getText();
              streetname1 = streetName.getText();
              town1 = town.getText();
              postcode1 = postcode.getText();
              beds1 = beds.getText();
              price1 = price.getText();
              type1 = type.getText();

            inputdata = housenumber1 + " " + streetname1 + " " + town1 + " " + 

            postcode1 +" " + beds1 + " " + price1 + " " + type1;

             writeto write = new writeto();
             dispose();
            }
       });
    }

Solution

  • You would benefit greatly from using a database as opposed to a text file. Further your question displays a fundamental lack of knowledge of not only Swing, but basic CRUD (Create, Read, Update, Delete) functionality.

    To answer your question you can clear your text field with textField1.setText("");

    I would read up on using a database for storing data. It will make life much easier for you.