[英]Save JTextField inputs to text file
我有一個為用戶信息創建的表格。 我需要輸入到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);
}
我會這樣寫代碼(在您定義文本字段的函數中,以您在問題中顯示的方法為例):
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,則還必須使用/而不是\\)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.