2016-11-06 117 views
0

我學習AWT並提出一個applet,將保存在一個文件如何打印的getText()後提交

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(); 
} 
} 

信息是我錯了與文件寫入或者我沒有成功的gettext?我無法在txt文件上打印任何內容。文件寫入失敗時會出現標籤嗎?我很苦惱Java。

+0

你得到任何異常? – aleb2000

+0

@ aleb2000沒有出現,順便說一句,如果我沒有錯那麼我會有一個錯誤標籤,如果有例外的權利? –

+0

無論如何,我的第一個建議是在'actionPerform()'方法內部調試,看看你的程序是否真的進入了if語句。 – aleb2000

回答

1

你有2個缺點:

  • 方法名重寫是actionPerformed
  • 您不能添加throws Exception,因爲原來的方法不扔東西。

你應該寫這個方法:

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

你寫了一個從未使用的AWT框架的方法。

+0

我不明白是怎麼OP甚至獲取代碼*編譯*給出的拼寫錯誤的方法名。我能想到的唯一的事情是,他們忽略了錯誤的IDE的報告,並允許運行的代碼,不正確編譯。 (反對使用這種IDE的好例子 - 即使在專家手中也是危險的。) –