【问题标题】:How to print to file after getText()getText() 后如何打印到文件
【发布时间】: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())。

标签: java file output awt


【解决方案1】:

你有两个错误:

  • 要覆盖的方法名称是actionPerformed
  • 您不能添加throws Exception,因为原始方法不会抛出任何东西。

你应该写这个方法:

@Override
public void actionPerformed(ActionEvent evt) {
  // ...
}

您编写了一个 AWT 框架从未使用过的方法。

【讨论】:

  • 鉴于拼写错误的方法名称,我无法理解 OP 是如何让代码编译的。我唯一能想到的是他们忽略了他们的 IDE 错误正在报告,它允许运行无法正确编译的代码。 (反对使用这种 IDE 的一个很好的例子——即使在专家手中也很危险。)
猜你喜欢
  • 1970-01-01
  • 2012-11-01
  • 2014-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-24
  • 1970-01-01
相关资源
最近更新 更多