Search code examples
javaswingfile-ioactionlistenerjtextfield

Creating a new file using JTextField


Hi I'm having trouble taking the user input and making it receive user input. Then taking the user input and using it to create a new text blank text file. I can get it to work but when I use JTextField it won't create the file.

Any help would be greatly appreciated.

This is my code:

import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JOptionPane;
import javax.swing.*;
import java.io.*;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.util.Scanner;

public class newGame extends JFrame {
    private JButton reg;
    private JTextField userName;
    private JTextField info;
    Scanner input = new Scanner(System.in);

    public newGame() {

        super ("Rock Paper Scissors");

        //creates the text fields
        info = new JTextField ("Welcome to the rock, Please enter your username below");
        info.setEditable(false);
        JTextField userName = new JTextField ("name");

        //impliments actionlistner
        newClass saver = new newClass();
        userName.addActionListener(saver);


        //adds the fields to the Content Layout
        JPanel content = new JPanel();
        content.setLayout(new BorderLayout());
        content.add(info, BorderLayout.NORTH);
        content.add(userName, BorderLayout.SOUTH);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setContentPane(content);
        setTitle("Rock Paper Scissors The Game");
        pack();


    }


    private class newClass implements ActionListener {
        public void actionPerformed (ActionEvent event) {

            String newUserName = userName.getText();
            File file = new File(newUserName + ".txt");
            boolean blnCreated = false;
            try {
                blnCreated = file.createNewFile();
            } catch(IOException ioe) {
            }
            JOptionPane.showMessageDialog
                (null,String.format("%s",event.getActionCommand()));
        }
    }
}

Solution

  • You're shadowing the variable userName so the class member variable of the same name is never set resulting in an NPE in the ActionListener before the file can be created. Replace

    JTextField userName = new JTextField("name");
    

    with

    userName = new JTextField("name");