【问题标题】:Search Data in an ArrayList that saved in a file and print it out in a texfield在保存在文件中的 ArrayList 中搜索数据并在 texfield 中打印出来
【发布时间】:2013-05-30 03:57:15
【问题描述】:

我有这个按钮,可以通过 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 的文本字段,我如何在数组列表中搜索帐号?当Withdraw_AccountNumber 与arraylists 中的账号匹配时,也会在Withdraw_AccountName 中显示账户名。请帮忙。

【问题讨论】:

    标签: java swing arraylist textfield


    【解决方案1】:

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

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

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

    【讨论】:

    • 我希望它们被存储为ints ;)
    • 您好,您能帮我看看缺少什么吗?我也只想显示账户名private void txt_wdaccountnumberActionPerformed(java.awt.event.ActionEvent evt) { for(BankAccount account: list){ if(account.getAccountNo() == txt_wdaccountnumber.getText()){ //get the accontname and display it in txt_wdaccountname } else{ JOptionPane.showMessageDialog(this, "No records found!"); } } // TODO add your handling code here: }
    • 我尝试了以下但没有任何反应。 private void txt_wdaccountnumberActionPerformed(java.awt.event.ActionEvent evt) { for(BankAccount account: list){ if(account.getAccountNo().equals(txt_wdaccountnumber.getText())){ txt_wdaccountname.setText(account.getAccountName()); txt_wdaccountname } else{ JOptionPane.showMessageDialog(this, "No records found!");
    • 什么都没有发生是什么意思?帐号也是文本字段还是原语?
    • 帐号是一个文本字段。我尝试将代码放在txt_wdaccountnumber的actionevent中,当用户在txt_wdaccountnumber中输入一个数字时,它会在arraylist中搜索帐号,当它找到时,与该帐号关联的帐户名也会显示在txt_wdaccountname中,但似乎我错过了什么或没有工作?
    猜你喜欢
    • 1970-01-01
    • 2014-04-25
    • 2022-08-02
    • 1970-01-01
    • 2013-04-04
    • 2015-10-17
    • 1970-01-01
    • 2014-03-25
    • 2017-08-10
    相关资源
    最近更新 更多