【发布时间】:2016-11-06 16:08:57
【问题描述】:
我正在学习 AWT,并制作了一个可以将信息保存在文件中的小程序
import practice1.AccountRecord;
public class GUI extends Frame implements ActionListener{
Label account_number = new Label("Account number");
Label first_name = new Label("First name");
Label last_name = new Label("Last name");
Label account_balance = new Label("Balance");
TextField account = new TextField(20);
TextField first = new TextField(20);
TextField last = new TextField(20);
TextField balance = new TextField(20);
Button save = new Button("Save into File...");
Button enter = new Button("Enter");
GUI(){
this.setTitle("Bank account");
this.setLayout(new FlowLayout());
this.add(account_number);
this.add(account);
this.add(first_name);
this.add(first);
this.add(last_name);
this.add(last);
this.add(account_balance);
this.add(balance);
this.add(save);
this.add(enter);
save.addActionListener(this);
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent evt)
{System.exit(0);}
});
}
public void actionPerform(ActionEvent evt) throws Exception{
AccountRecord record = new AccountRecord();
if(evt.getSource()==save)
{
record.accountNumber = Integer.parseInt(account.getText());
record.firstName = first.getText();
record.lastName = last.getText();
record.balance = Integer.parseInt(balance.getText());
try{
File f = new File("D:\\AccountRecord");
FileWriter fw = new FileWriter(f);
fw.write(record.accountNumber);
fw.write(record.firstName);
fw.write(record.lastName);
fw.write(record.balance);
fw.close();
}
catch(Exception e)
{
Label err = new Label("Error");
add(err);
}
}
}
public static void main(String args[]){
GUI ct = new GUI();
ct.resize(300,200);
ct.show();
}
}
我是文件写入有问题还是我没有成功获取文本?我无法在 txt 文件上打印任何内容。当文件写入失败时,标签会出现吗?我在使用 Java 时很吃力。
【问题讨论】:
-
你有什么异常吗?
-
@aleb2000 什么都没出现,顺便说一句,如果我没记错的话,如果有异常,我会有一个错误标签,对吧?
-
无论如何,我的第一个建议是在
actionPerform()方法中进行调试,看看你的程序是否真的进入了 if 语句。 -
另外,由于您只使用一个动作侦听器,我认为您不需要检查
if(evt.getSource() == save) -
在这里运行良好。错误标签不会以这种方式可见。首先,将
System.err.println(e);添加到 ecxpetion 捕获块。可能您无法写信给D:\\AccountRecord,或者存在格式错误(parseInt())。