2013-05-28 52 views
0

嗨我无法接受用户输入并使其收到用户输入。 然后接受用户输入并使用它来创建新的文本空白文本文件。 我可以得到它的工作,但是当我使用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())); 
     } 
    } 
} 

回答

2

shadowing变量userName所以同一个名字的类成员变量从未导致在ActionListenerNPE可以创建文件之前。更换

JTextField userName = new JTextField("name"); 

userName = new JTextField("name"); 
+0

非常感谢你,帮助!当地的影子。 –