0

I'm having a big headache with a college project. Im doing a bank app and im having problems with the making a list of accounts and storing the info.

This is the class im working with, it gets the account number, name, some identification from the user, the money sum inside the account and the password:

public class Conta {
    private int NumConta;
    private String Nome;
    private String RG;
    private String CPF;
    private double Saldo;
    private String Password;

    public Conta(int NumConta, String Nome, String RG, String CPF, double Saldo, String Password) {
        this.NumConta = NumConta;
        this.Nome = Nome;
        this.RG = RG;
        this.CPF = CPF;
        this.Saldo = Saldo;
        this.Password = Password;
    }

    Conta() {
    }

    public int getNumConta() {
        return NumConta;
    }

    public void setNumConta(int NumConta) {
        this.NumConta = NumConta;
    }

    public String getNome() {
        return Nome;
    }

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

    public String getRG() {
        return RG;
    }

    public void setRG(String RG) {
        this.RG = RG;
    }

    public String getCPF() {
        return CPF;
    }

    public void setCPF(String CPF) {
        this.CPF = CPF;
    }

    public double getSaldo() {
        return Saldo;
    }

    public void setSaldo(double Saldo) {
        this.Saldo = Saldo;
    }

    public String getPassword() {
        return Password;
    }

    public void setPassword(String Password) {
        this.Password = Password;
    }

}

This here below is the jframe I use register new accounts. The user enters the info and when he clicks the button it should get all the info from the text lines and send it to addFunc so the info can be stored in the list. Note that i have a "for" there only for the purpose of seeing whats happening with the list. It gets the information and prints to the console, but if i make a new entry, it either overwrites or something else happens, because i can only see the last registration entered:

package banco_projeto;

import java.util.Random;
import javax.swing.JOptionPane;

public class Cadastrar extends javax.swing.JFrame {

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

        jPanelinicio = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jTextFieldnomecadastro = new javax.swing.JTextField();
        jTextFieldRG = new javax.swing.JTextField();
        jTextFieldCPF = new javax.swing.JTextField();
        jTextFieldpasswordcadastro = new javax.swing.JTextField();
        jButtonconfirmarcadastro = new javax.swing.JButton();
        jButtonvoltarCadastrar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanelinicio.setBackground(new java.awt.Color(102, 153, 255));

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));

        jLabel1.setText("RG:");

        jLabel2.setText("CPF:");

        jLabel3.setText("Nome:");

        jLabel4.setText("Password:");

        jButtonconfirmarcadastro.setText("Confirmar");
        jButtonconfirmarcadastro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonconfirmarcadastroActionPerformed(evt);
            }
        });

        jButtonvoltarCadastrar.setText("Voltar");
        jButtonvoltarCadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonvoltarCadastrarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addComponent(jLabel4))
                .addGap(58, 58, 58)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextFieldpasswordcadastro, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldCPF, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldRG, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldnomecadastro, javax.swing.GroupLayout.PREFERRED_SIZE, 255, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(77, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jButtonconfirmarcadastro, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jButtonvoltarCadastrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(173, 173, 173))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(56, 56, 56)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldnomecadastro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(47, 47, 47)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldRG, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(43, 43, 43)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextFieldCPF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(40, 40, 40)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addComponent(jTextFieldpasswordcadastro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(68, 68, 68)
                .addComponent(jButtonconfirmarcadastro)
                .addGap(18, 18, 18)
                .addComponent(jButtonvoltarCadastrar)
                .addContainerGap(28, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanelinicioLayout = new javax.swing.GroupLayout(jPanelinicio);
        jPanelinicio.setLayout(jPanelinicioLayout);
        jPanelinicioLayout.setHorizontalGroup(
            jPanelinicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanelinicioLayout.setVerticalGroup(
            jPanelinicioLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanelinicioLayout.createSequentialGroup()
                .addGap(0, 117, Short.MAX_VALUE)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelinicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanelinicio, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
        );

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

    private void jButtonvoltarCadastrarActionPerformed(java.awt.event.ActionEvent evt) {                                                       
        Principal principal = new Principal();
        principal.setVisible(true);           
        dispose();
    }                                                      

    private void jButtonconfirmarcadastroActionPerformed(java.awt.event.ActionEvent evt) {                                                         
        Random random = new Random();
        int numero = random.nextInt(9999999);
        Conta conta = new Conta(numero,jTextFieldnomecadastro.getText(),jTextFieldRG.getText(),jTextFieldCPF.getText(),0,jTextFieldpasswordcadastro.getText());
        Control control = new Control();
        control.AddFunc(conta);
        JOptionPane.showMessageDialog(this, "Conta criada com sucesso!\n"+"Numero da conta: "+numero);
                        for(int i = 0; i<control.listaContas.size();i++){
                             System.out.println("info na lista dentro for : "+control.listaContas.get(i).getCPF()+"\nindice do i"+i);
                        }

        Principal p = new Principal();
        p.setVisible(true);
        dispose();
    }                                                        

    /**
     * @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(Cadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Cadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Cadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Cadastrar.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

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

    // Variables declaration - do not modify                     
    private javax.swing.JButton jButtonconfirmarcadastro;
    private javax.swing.JButton jButtonvoltarCadastrar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanelinicio;
    private javax.swing.JTextField jTextFieldCPF;
    private javax.swing.JTextField jTextFieldRG;
    private javax.swing.JTextField jTextFieldnomecadastro;
    private javax.swing.JTextField jTextFieldpasswordcadastro;
    // End of variables declaration                   
}

This is the class i made to keep the list of accounts and made a add function to add elements to the list

package banco_projeto;

import java.util.ArrayList;

public class Control {
    ArrayList<Conta> listaContas = new ArrayList();
    Conta conta = new Conta();

    public Conta getConta() {
        return conta;
    }

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

    public ArrayList<Conta> getListaContas() {
        return listaContas;
    }

    public void setListaContas(ArrayList<Conta> listaContas) {
        this.listaContas = listaContas;
    }
        public void AddFunc(Conta conta){        
        //System.out.println("info na variavel conta: "+conta.getNumConta());
        listaContas.add(conta); 
        //System.out.println("info na lista pos zero : "+listaContas.get(0).getNumConta());
    }

}

I still have a couple other jframes, but im not sure if they are relevant to my problem. Am i building the list incorrectly? What is happening with my list? Is it because im creating the objects inside the methods? Is it working and im just not knowing how to manupulate a list? I tried several different approaches but nothing changed. If you could provide me with an example on how to fix this I'll be very grateful.

Thanks in advance!

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
WildDracula
  • 31
  • 1
  • 1
  • 5
  • You're creating a new Control object every time the ActionListener is called -- are you sure that you want to be doing that? Don't you want to create a single Control object and then within the ActionListener add the new Contra to it? – Hovercraft Full Of Eels May 03 '20 at 16:39
  • @HovercraftFullOfEels Just tried moving the "Control control = new Control();" outside of the method, but it still rewrites the list. When i try to create 2 different accounts it writes it over the [0] index of the list. Did i not understand what you said correctly? – WildDracula May 03 '20 at 16:46
  • Do you create multiple Cadastrar instances? Or do you create only one and test the contents of Control? – Hovercraft Full Of Eels May 03 '20 at 16:49
  • @HovercraftFullOfEels I create one, it does its job and closes (with dispose();). Then I call the Cadastrar jframe again (from a button in another jframe) and create a second account. I tried not disposing of the Cadastrar jframe, kept it open, but result is the same. Should i show the jframe from where Cadastrar is called? – WildDracula May 03 '20 at 17:00
  • As I suspected. The solution is as per my answer. Note that Fabian's answer just repeats what I mentioned in the earlier comment and is incomplete. – Hovercraft Full Of Eels May 03 '20 at 17:03

2 Answers2

3

Issues:

  • As mentioned in my comment, the Control object should not be made within the listener
  • If you create multiple Cadastrar objects, then the Control object should not be created within this class.
  • Rather, it should be made in a non-GUI model class, and passed into Cadastrar via a constructor parameter, setting a field. For example:

    public class Cadastrar extends javax.swing.JFrame {
        Control control;
    
        public Cadastrar(Control control) {
            this.control = control;
            initComponents();
        }
    
  • Cadastrar Shouldn't be a JFrame but rather a JDialog, possibly a model JDialog

  • And if so, the controlling class should control which windows to display next, not Cadastrar. See: The Use of Multiple JFrames: Good or Bad Practice?

In comment you state:

I create one, it does its job and closes (with dispose();). Then I call the Cadastrar jframe again (from a button in another jframe) and create a second account. I tried not disposing of the Cadastrar jframe, kept it open, but result is the same. Should i show the jframe from where Cadastrar is called?

Exactly as I thought -- each time you create a new Cadastrar object, you create a new Control object and all data previously held vanishes. The solution is as I mentioned above -- create one Control object and pass it where needed.

Your program design is also not sound as you really should think about separating the non-GUI program logic, the "model", from the GUI portion, the "view", and you don't want to sling multiple JFrames at the poor user as that can be quite annoying to the user. Think about most professional software that you use, and few will throw multiple windows at the user. Better to swap views via a CardLayout with occasional dialog (JDialog) windows rather than multiple main program (JFrame) windows. There should be a single JFrame that displays throughout the program's life.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • Okay, so i moved the Control object outside the listener. I dont create any Cadastrar objects. It is a frame sololy for registration and it doesnt hold any informations, it gets what the user put in the jText, puts the info inside the object conta created from Conta(which holds the constructor with different variables such as name, password, account number, etc..), then sends this variable (with the informations) to Control, where it is added to the list. Control is a simples class, not a jFrame Im very new to this tho, so im very thankful for the useful link provided, will sure read it! – WildDracula May 03 '20 at 17:11
  • I was referring to `Principal p = new Principal();` and I'm betting that Principal is a JFrame object which is the next JFrame being shown the user. – Hovercraft Full Of Eels May 03 '20 at 17:13
  • Principal is the "welcome screen". The welcome screen has a few options, log-in and register. When the user chooses register "Cadastrar", it goes to Cadastrar and asks the info. After submitting the info Cadastrar closes and goes back to the welcome screen. Where the user should now be able to choose login and proceed. So the act of opening and closing Cadastrar is making new lists? Even tho the list is stored in a different class (Control)? Gonna learn about CardLayouts! Thanks for the tip – WildDracula May 03 '20 at 17:24
1

Your problem is in here:

Control control = new Control();
control.AddFunc(conta);
JOptionPane.showMessageDialog(this, "Conta criada com sucesso!\n"+"Numero da conta: "+numero);
    for(int i = 0; i<control.listaContas.size();i++){
        System.out.println("info na lista dentro for : "+control.listaContas.get(i).getCPF()+"\nindice do i"+i);
    }

Every time the jButtonconfirmarcadastroActionPerformed Method is called you create a new Control, add the currently created Conta to it and then print you list. Next time you create a new one and prin it again.

Instead you have to create the control Variable outside the method and initiate it. The in the jButtonconfirmarcadastroActionPerformed do not create a new one but instead access the one defined outside the method.

Fabian Zimbalev
  • 493
  • 4
  • 12
  • I put "Control control = new Control();" outside the method but it still prints the same thing. Did i not understand what you said correctly? – WildDracula May 03 '20 at 17:01