将JTextField输入保存到文本文件

时间:2016-04-06 18:57:24

标签: java swing

我有一个为用户信息创建的表单。我需要输入JTextFields的数据保存到文本文件中。我有这个动作监听器,按下按钮时构建GUI。需要帮助保存数据......

        static class Register implements ActionListener {

        public void actionPerformed (ActionEvent e){
            //Creates new JPanel 
            JFrame rFrame = new JFrame ("Register, Please Enter Your Information.");
            rFrame.setVisible(true);
            rFrame.setSize(800,800);
            JPanel rPanel = new JPanel(new GridLayout(0,2));
            rFrame.add(rPanel);

            //Creates register form
            JLabel Rfirstname = new JLabel("Firstname: "); rPanel.add(Rfirstname);
            JTextField firstname = new JTextField(40); rPanel.add(firstname);
            JLabel Rsurname = new JLabel("Surname: "); rPanel.add(Rsurname);
            JTextField surname = new JTextField(40); rPanel.add(surname);
            JLabel Rdob = new JLabel("D.O.B: "); rPanel.add(Rdob);
            JTextField dob = new JTextField(40); rPanel.add(dob);
            JLabel Raddress = new JLabel("Address: "); rPanel.add(Raddress);
            JTextField address = new JTextField(40); rPanel.add(address);
            JLabel Rpostcode = new JLabel("Post Code: "); rPanel.add(Rpostcode);
            JTextField postcode = new JTextField(40); rPanel.add(postcode);
            JLabel Rallergy = new JLabel("Allergy Info: "); rPanel.add(Rallergy);
            JTextField allergy = new JTextField(40); rPanel.add(allergy);
            JLabel Rcontact = new JLabel("Contact Details: "); rPanel.add(Rcontact);
            JTextField contact = new JTextField(40); rPanel.add(contact);

    }

1 个答案:

答案 0 :(得分:4)

我会像那样编写代码(在你定义文本字段的函数中,在你的问题中显示的方法中):

JTextField firstName=new JTextField();
    JButton but=new JButton("Save");
    but.addActionListener(e1->{
        try{
            BufferedWriter bw = new BufferedWriter(new FileWriter("asdf.txt"));
            bw.write(firstName.getText());
            bw.close();
        }catch(Exception ex){
            ex.printStackTrace();
        }
    });

在这个例子中,我只是写了firstName的文本。如果你想写所有字段,你必须连接它们(或类似的东西。 此外,您必须修改路径(如果使用Windows,则还必须使用/而不是\作为路径)。