我有一个为用户信息创建的表格。我需要输入到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);
}
Run Code Online (Sandbox Code Playgroud)
我会这样写代码(在您定义文本字段的函数中,以您在问题中显示的方法为例):
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();
}
});
Run Code Online (Sandbox Code Playgroud)
在此示例中,我只写了firstName的文本。如果要编写所有字段,则必须连接它们(或类似内容。此外,还必须修改路径(如果使用Windows,则还必须使用/而不是\))。