Reading user's input from a JOptionPane and store it in a text file

1.2k views Asked by At

I want to read user's input (user's nickname) from a JOptionPane and then store that input into a new txt file. Also, I want the entered information to update itself in the text file every time a new user enters his nickname. Thank you very much in advance for the help! Here is my code:

private static class testItApp implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {

        String filename = "scoreboard.txt";

        try {    
            PrintWriter output = new PrintWriter(filename);
            JOptionPane.showInputDialog(null, "Enter your nickname:");
            output.println("kjkjbkj");
            output.close();
        } 
        catch (FileNotFoundException ex) {
            System.out.println("Error");
        }          
    }
}
1

There are 1 answers

2
MadProgrammer On BEST ANSWER

JOptionPane.showInputDialog returns the value the user entered into the field or null if the canceled the dialog. Assign and check the return result

String nickName = JOptionPane.showInputDialog(null, "Enter your nickname:");
if (nickName != null) {
    // Save it...
}

See How to Make Dialogs and JOptionPane#showInputDialog for more details