我有一个按钮,可以通过ArrayLists中的文本字段保存输入数据并将其保存到文件中。
private void btnSaveAActionPerformed(java.awt.event.ActionEvent evt) {
BankAccount account = new BankAccount();
ButtonGroup bg = new ButtonGroup();
bg.add(rad_savings);
bg.add(rad_checking);
account.setAccountName(txt_accountname.getText());
account.setAccountNo(txt_accountnumber.getText());
list.add(account);
String fileName = "bank.txt";
FileWriter file = null;
try {
file = new FileWriter(fileName,true);
PrintWriter pw = new PrintWriter(file);
for(BankAccount str: list) {
pw.println(str);
}
pw.flush();
pw.println("\n");
} catch(FileNotFoundException ex) {
JOptionPane.showMessageDialog(this, "Can't create your account!");
} catch (IOException ex) {
Logger.getLogger(JFrameNewAccount.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
file.close();
} catch (IOException ex) {
Logger.getLogger(JFrameNewAccount.class.getName()).log(Level.SEVERE, null, ex);
}
}
我还有一个Withdraw_AccountName和Withdraw_AccountNumber的文本字段,如何搜索arraylists中的帐号?当Withdraw_AccountNumber与arraylists中的帐号匹配时,它还将在Withdraw_AccountName中显示帐户名。请帮忙。
答案 0 :(得分:1)
您需要遍历BankAccounts才能找到具有您需要的帐号的那个。
for(BankAccount account: list) {
if (account.getAccountNo().equals(accountNumberToSearchFor)){
// found ya! set the correct text field
break;
}
}
或者,您可以将BankAccounts存储在地图中,您可以在其中为银行帐户创建帐号的地图;或者,您也可以创建自定义比较器并使用现在按帐号排序的Java Collection。