Recover / locate object in arraylist

2

I am doing a small CRUD with the theme saving for study purposes. I created 3 classes: Savings, Accounts and Screen (UI Swing).

On the screen I register an account with the attributes name, agency, account number (the balance starts with value 0 by default), according to the constructor.

The problem: I can not retrieve the data in the query or remove account for example methods. Either return the name entered in the UI at the time of the search or return nothing.

What do I need: Enter the name of the holder of a Savings account (object) and the name of the system to search the ArrayList accounts . If you find the name, return the object (the account) that has this name as an attribute (and display the data of that account in TextArea), otherwise return null.

obs: The Query 2 method is another query attempt. But I believe the error is in the main class (Tela.java). I have the impression that something is wrong with the button methods, but I could not solve it. I tried to create the object in the scope of the class, I tried to create direct in the scope of the methods of the buttons, etc ... nothing is certain.

Class Savings.java

package classes;

public class Poupanca {

    private String nome;
    private String Agencia;
    private String Conta;
    private double saldo;

    public Poupanca(String nome) {
        this.nome = nome;
    }

    public Poupanca(String nome, String Agencia, String Conta, double saldo) {
        this.nome = nome;
        this.Agencia = Agencia;
        this.Conta = Conta;
        this.saldo = saldo;
    }

    public void sacarDinheiro(double valor) throws Exception {
        if (valor > this.saldo) {
            throw new Exception("Saldo insuficiente");
        }
        this.saldo -= valor;
    }

    public void depositarDinheiro(double valor) throws Exception {
        if (valor <= 0) {
            throw new Exception("Não é possível deposito nulo ou negativo.");
        }
        this.saldo += valor;
    }

    public double getSaldo() {
        return saldo;
    }

    public String getNome() {
        return nome;
    }

    public void setNome(String nome) {
        this.nome = nome;
    }

    public String getAgencia() {
        return Agencia;
    }

    public void setAgencia(String Agencia) {
        this.Agencia = Agencia;
    }

    public String getConta() {
        return Conta;
    }

    public void setConta(String Conta) {
        this.Conta = Conta;
    }

}

Class Accounts.java

package classes;

import java.util.ArrayList;
import java.util.Iterator;

public class Contas {

    private ArrayList<Poupanca> contas = new ArrayList();

    public void cadastrarConta(Poupanca poup) {
        contas.add(poup);
    }

    public Poupanca consultarConta(Poupanca poup) {
        int posicao = contas.indexOf(poup);
        if (posicao >= 0) {
            return contas.get(posicao);
        }
        return null;
    }

    public Poupanca consultar2(String nome) {
        Iterator<Poupanca> it = contas.iterator();
        while (it.hasNext()) {
            Poupanca contato = it.next();
        }
        return null;
    }

    public void removerConta(Poupanca poup) {
        int posicao = contas.indexOf(poup);
        contas.remove(posicao);
    }

    public String numeroDeContas() { //apenas para curiosidade, mostra a quantidade de contas cadastradas a cada inserção efetivada
        return contas.size() + "";
    }

}

Full screen.java class:

package GUI;

import javax.swing.JOptionPane;
import classes.Poupanca;
import classes.Contas;

public class Tela extends javax.swing.JFrame {

    String nome = "";
    String agencia = "";
    String conta = "";
    String valorOperacao = "";
    Contas contas = new Contas();
    Poupanca poup;

    public Tela() {
        initComponents();
        setLocationRelativeTo(null);
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        tfNome = new javax.swing.JTextField();
        tfAgencia = new javax.swing.JTextField();
        tfConta = new javax.swing.JTextField();
        botaoCadastrarConta = new javax.swing.JToggleButton();
        botaoConsultarConta = new javax.swing.JButton();
        botaoExcluirConta = new javax.swing.JButton();
        botaoDepositar = new javax.swing.JButton();
        botaoSacar = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        tfValorOperacao = new javax.swing.JTextField();
        labelTotalContas = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        taSaida = new javax.swing.JTextArea();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("P O U P A N C A 1.0");

        jLabel1.setFont(new java.awt.Font("Trebuchet MS", 1, 36)); // NOI18N
        jLabel1.setText("POUPANÇA");

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel2.setText("Nome:");

        jLabel3.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel3.setText("Agência:");

        jLabel4.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel4.setText("Conta:");

        botaoCadastrarConta.setText("Cadastrar Conta");
        botaoCadastrarConta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoCadastrarContaActionPerformed(evt);
            }
        });

        botaoConsultarConta.setText("Consultar Conta");
        botaoConsultarConta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoConsultarContaActionPerformed(evt);
            }
        });

        botaoExcluirConta.setText("Excluir Conta");
        botaoExcluirConta.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoExcluirContaActionPerformed(evt);
            }
        });

        botaoDepositar.setText("Depositar");
        botaoDepositar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                botaoDepositarActionPerformed(evt);
            }
        });

        botaoSacar.setText("Sacar");

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel5.setFont(new java.awt.Font("Arial", 1, 12)); // NOI18N
        jLabel5.setText("Valor da Operação:");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(75, 75, 75)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(tfValorOperacao, javax.swing.GroupLayout.PREFERRED_SIZE, 87, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(tfValorOperacao, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(botaoCadastrarConta, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(botaoConsultarConta, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(botaoExcluirConta, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(10, 10, 10)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(tfAgencia, javax.swing.GroupLayout.DEFAULT_SIZE, 70, Short.MAX_VALUE)
                                .addComponent(tfConta))
                            .addComponent(tfNome, javax.swing.GroupLayout.PREFERRED_SIZE, 326, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(20, 20, 20)))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(botaoDepositar, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(14, 14, 14)
                        .addComponent(botaoSacar, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(19, 19, 19)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(tfNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(tfAgencia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(tfConta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(botaoConsultarConta)
                    .addComponent(botaoCadastrarConta)
                    .addComponent(botaoExcluirConta)
                    .addComponent(botaoDepositar)
                    .addComponent(botaoSacar))
                .addContainerGap())
        );

        labelTotalContas.setText("Contas Cadastradas: 0");

        taSaida.setEditable(false);
        taSaida.setColumns(20);
        taSaida.setRows(5);
        jScrollPane1.setViewportView(taSaida);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(238, 238, 238))
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(labelTotalContas)
                                .addContainerGap())))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 124, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(labelTotalContas)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>                        

    private void botaoCadastrarContaActionPerformed(java.awt.event.ActionEvent evt) {                                                    

            nome = tfNome.getText();
            agencia = tfAgencia.getText();
            conta = tfConta.getText();

            contas.cadastrarConta(poup = new Poupanca(nome, agencia, conta, 0));

            JOptionPane.showMessageDialog(rootPane, "Conta Cadastrada com sucesso!", "Parabéns!", HEIGHT);

            labelTotalContas.setText("Contas Cadastradas: " + contas.numeroDeContas());

            String limpa = "";
        tfNome.setText(limpa);
        tfAgencia.setText(limpa);
        tfConta.setText(limpa);

    }                                                   

    private void botaoConsultarContaActionPerformed(java.awt.event.ActionEvent evt) {                                                    

//        try {
            nome = tfNome.getText();

            contas.consultarPorNome(nome);

            taSaida.setText("Nome: " + poup.getNome() + "\nAgência: " + poup.getAgencia() + "\nConta: " + poup.getConta() + "\nSaldo: "
                    + poup.getSaldo());

//        } catch (Exception E) {
//            JOptionPane.showMessageDialog(rootPane, "Campo nome não pode ficar vazio!", E.getMessage(), 2);
//        }

        String limpa = "";
        tfNome.setText(limpa);
        tfAgencia.setText(limpa);
        tfConta.setText(limpa);

    }                                                   

    private void botaoExcluirContaActionPerformed(java.awt.event.ActionEvent evt) {                                                  

        nome = tfNome.getText();
        Poupanca poup = new Poupanca(nome);
        contas.removerConta(poup);

        String limpa = "";
        tfNome.setText(limpa);
        tfAgencia.setText(limpa);
        tfConta.setText(limpa);
        taSaida.setText(limpa);
    }                                                 

    private void botaoDepositarActionPerformed(java.awt.event.ActionEvent evt) {                                               

        try {

        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, e.getMessage(), "ATENÇÃO!", 2);
        }

    }                                              

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Tela.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Tela().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify                     
    private javax.swing.JToggleButton botaoCadastrarConta;
    private javax.swing.JButton botaoConsultarConta;
    private javax.swing.JButton botaoDepositar;
    private javax.swing.JButton botaoExcluirConta;
    private javax.swing.JButton botaoSacar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel labelTotalContas;
    private javax.swing.JTextArea taSaida;
    private javax.swing.JTextField tfAgencia;
    private javax.swing.JTextField tfConta;
    private javax.swing.JTextField tfNome;
    private javax.swing.JTextField tfValorOperacao;
    // End of variables declaration                   

}

The graphical interface:

    
asked by anonymous 13.03.2018 / 10:24

3 answers

1

You could do this as follows:

Class Accounts

public Poupanca consultarPorNome(String nome) {

        /* Essa linha abaixo é legal utilizar, pois você usa Lambda e é uma coisa nova
         * já que você esta aprendendo, porém, só da para utilizar com Java acima da Versão 8.
         * 
         * return contas.stream().filter(x -> x.getNome().equals(nome)).findFirst().get();*/

        // Se não for uma versão igual ou acima da 8, você pode fazer o famoso Foreach
        for(Poupanca poupanca : contas) {
            if(poupanca.getNome().equals(nome)){
               return poupanca; 
            }
        }

        return null;
    }

Screen Class

    private void botaoConsultarContaActionPerformed(java.awt.event.ActionEvent evt) {

        nome = tfNome.getText();

        Poupanca contaDoUsuario = contas.consultarPorNome(nome);
        if (contaDoUsuario != null) {

            taSaida.setText("Nome: " + contaDoUsuario.getNome() + "\nAgência: " + contaDoUsuario.getAgencia() + "\nConta: "
                    + contaDoUsuario.getConta() + "\nSaldo: " + contaDoUsuario.getSaldo());
        } else {
            System.out.println("Não existe uma conta para esse nome");
        }

        String limpa = "";
        tfNome.setText(limpa);
        tfAgencia.setText(limpa);
        tfConta.setText(limpa);
    } // Continue usando o seu Try Catch, só queria representar a validação do caso "null" para poupança
    
13.03.2018 / 14:50
3

You can do the search method by name as follows:

public Poupanca consultarPorNome(String nome) {

    for(Poupanca p : contas) {
        if(p.getNome().equals(nome)){
           return p; 
        }
    }
    return null;

The method will be named in the form of a string and within the loop on the list of accounts, we will check if any account has that name. When it is found, we return the account and break the loop.

To use, just invoke this method on the button where you call the search by name on your screen:

private void botaoConsultarContaActionPerformed(java.awt.event.ActionEvent evt) {

    try {
        nome = tfNome.getText();
        this.poup = contas.consultarPorNome(nome);
        taSaida.setText("Nome: " + poup.getNome() + "\nAgência: " + poup.getAgencia() + "\nConta: "
                + poup.getConta() + "\nSaldo: " + poup.getSaldo());
    } catch (Exception E) {
        JOptionPane.showMessageDialog(rootPane, "Campo nome não pode ficar vazio!", E.getMessage(), 2);
    }

    String limpa = "";
    tfNome.setText(limpa);
    tfAgencia.setText(limpa);
    tfConta.setText(limpa);
}

Your code has many problems like this poup variable that has no need to be class, but only local, and other unhandled operations problems that will pop out exception but will not go into detail to not distort the answer.     

13.03.2018 / 11:31
0
I'm glad you liked the way I put the question. Organization is essential in life. I saw the various errors Articuno, I left it to the end, because first I wanted to make the program work. The tips of you and Ricardo made sense. Thank you very much.

I'll put the methods of the buttons "register" and "consult" working if anyone has a similar question:

Register button

 private void botaoCadastrarContaActionPerformed(java.awt.event.ActionEvent evt) {                                                    
        try {
            nome = tfNome.getText();
            agencia = tfAgencia.getText();
            conta = tfConta.getText();

            Poupanca poup = new Poupanca(nome, agencia, conta, 0);

            contas.cadastrarConta(poup);

            JOptionPane.showMessageDialog(rootPane, "Conta cadastrada com sucesso!", "Parabéns!", 1);

            labelTotalContas.setText("Contas Cadastradas: " + contas.numeroDeContas());

        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, e.getMessage(), "ERRO!", 2);
        }

        String limpa = "";
        tfNome.setText(limpa);
        tfAgencia.setText(limpa);
        tfConta.setText(limpa);

    }          

Query button

private void botaoConsultarContaActionPerformed(java.awt.event.ActionEvent evt) {                                                    

        try {

            nome = tfNome.getText();
            Poupanca poup = new Poupanca(nome);

            poup = contas.consultarPorNome(nome);

            taSaida.setText("Nome: " + poup.getNome() + "\nAgência: " + poup.getAgencia() + "\nConta: " + poup.getConta() + "\nSaldo: "
                    + poup.getSaldo());

        } catch (Exception E) {
            JOptionPane.showMessageDialog(rootPane, E.getMessage(), "ERRO!", 2);
        }

        String limpa = "";
        tfNome.setText(limpa);
        tfAgencia.setText(limpa);
        tfConta.setText(limpa);

    }                        
    
16.03.2018 / 11:47