javajframeactionlistenerbuffered

Buffered writer is not writing text?


i am making a simple program that takes a username and password and saves it to a text file. however, the program works fine until i check the hard drive. the text file is there bu there is no text.

public class Main {


public static void main(String args[]){
    events jack = new events();


    events gui = new events();
    gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    gui.setTitle("WCPSS");
    gui.setSize(1100,400);
    gui.setVisible(true);
    gui.setLocationRelativeTo(null);

    BufferedWriter bw = null;
      try {

         //Specify the file name and path here
     File file = new File("E:/myfile.txt");

     /* This logic will make sure that the file 
      * gets created if it is not present at the
      * specified location*/
      if (!file.exists()) {
         file.createNewFile();
      }

      FileWriter fw = new FileWriter(file);
      bw = new BufferedWriter(fw);
      bw.write(jack.username);
          System.out.println("File written Successfully");

      } catch (IOException ioe) {
       ioe.printStackTrace();
    }
    finally
    {  
       try{
          if(bw!=null)
         bw.close();
       }catch(Exception ex){
           System.out.println("Error in closing the BufferedWriter"+ex);
        }
    }
}

}

public class events extends JFrame {

public String username = ("");
public String password = ("");
private JLabel label;
private JButton button;
private JTextField userin = new JTextField(10);
private JTextField userpass = new JTextField(10);


public events() {
    setLayout(new FlowLayout());

    button = new JButton("Submit");
    button.setBounds(5, 435, 50, 123);
    add(button);
    label = new JLabel(
            "Please enter your username and password : ");
    add(label);
    add(userin);
    add(userpass);

    button.addActionListener((e) -> {
        sumbitAction();
    });

}

private void sumbitAction() {
    username = userin.getText();
    password = userpass.getText();
    System.out.println(username);
    System.out.println(password);
}

}

i know that this is probably poorly writen, but i am a beginner and would apperticate some help. thank you


Solution

  • The part of writing to the file should work. The problem is it runs right after the JFrame is loaded.

    You should move the code to the ActionListener handler that executes when you press the JButton:

    private void sumbitAction() {
        username = userin.getText();
        password = userpass.getText();
        System.out.println(username);
        System.out.println(password);
    
        // do the writing here
    }
    

    You're also creating two instances of the JFrame in memory and loading only one. Why? Just create only one.