Retrieve/locate object in arraylist

Asked

Viewed 1,139 times

2

I am making a small CRUD with the theme saving for study purposes. I created 3 classes: Save, Accounts and Canvas (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 cannot recover the data in the methods query or remove account for example. Either returns the name entered in the UI at the time of the search or returns nothing.

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

Obs: the query method 2 is another query attempt. But I believe the error is in the main class (Canvas.java). I have a feeling there’s something wrong with the button methods, but I couldn’t fix it. I tried to create the object in the class scope, tried to create directly in the scope of the button methods, etc...nothing right.

Class Poupanca.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;
    }

}

Accounts class.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() + "";
    }

}

Screen class.java complete:

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: inserir a descrição da imagem aqui

  • Well organized your question, congratulations, it helps and very much the community.

3 answers

2

You can do the name search method as follows:

public Poupanca consultarPorNome(String nome) {

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

The method will receive the name in string form and within the loop over the list of accounts, we check if any account has that name. When found, we return the account and interrupt 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 variable poup that has no need to be class, but only local, and other untreated operations problems that will burst exception but I will not go into detail not to distort the answer.

1


You could do it this way:

Contas class

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

0

Glad you liked the way I put it. Organization is essential in life. I saw the various errors Articuno, I left to the end, because first I wanted to make the program work. It worked out your and Ricardo’s tips. Thank you very much.

I will put as it was the methods of the buttons "register" and "consult" working if someone has a similar question:

Sign-up 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);

    }          

Consult 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);

    }                        
  • 1

    It still has some structural problems that I wouldn’t do, as these methods do practically the same thing with a slight difference and you created two different listeners for them. Anyway, good studies :)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.