使用JTextField创建新文件

时间:2013-05-28 18:40:25

标签: java swing file-io actionlistener jtextfield

嗨,我无法接收用户输入并接收用户输入。 然后获取用户输入并使用它来创建新的文本空白文本文件。 我可以让它工作,但当我使用JTextField时,它不会创建该文件。

非常感谢任何帮助。

这是我的代码:

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()));
        }
    }
}

1 个答案:

答案 0 :(得分:2)

你是shadowing变量userName所以永远不会设置同名的类成员变量,导致NPE中的ActionListener在文件可以之前创建。取代

JTextField userName = new JTextField("name");

userName = new JTextField("name");