java - 搜索保存在文件中的 ArrayList 中的数据并将其打印在文本字段中

标签 java swing arraylist textfield

我有这个按钮,可以通过 ArrayList 中的文本字段保存输入数据并将其保存到文件中。

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 的文本字段,我如何在数组列表中搜索帐号?当Withdraw_AccountNumber与数组列表中的帐号匹配时,也会在Withdraw_AccountName中显示帐户名称。请帮忙。

最佳答案

您需要遍历 BankAccounts 以找到具有您所需帐号的银行帐户。

for(BankAccount account: list) {
    if (account.getAccountNo().equals(accountNumberToSearchFor)){
        // found ya! set the correct text field
        break;
    }
}

或者,您可以将 BankAccounts 存储在 Map 中,您可以在其中制作帐号到银行帐户的映射;或者,您也可以创建一个自定义比较器并使用现在按帐号排序的 Java 集合。

关于java - 搜索保存在文件中的 ArrayList 中的数据并将其打印在文本字段中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16827688/

相关文章:

Java Swing 范围 slider 用户界面

Java ArrayList 从并行线程中删除不存在的对象

java - 为什么数组被初始化为默认值而不是 java 中的 arraylist?

java - 允许多种预定义类型的集合

java - 枚举反射

java - 是第二个角左边或右边的角

java - 方法 add(Component) 不适用于参数

java - GLSL 着色器无法在 Mac 上运行

java Swing计时器依次执行几项任务

java - 如何从 ArrayList 填充报告?