英文:
Having problems with lists in java
问题
I'm having a big headache with a college project. I'm doing a bank app and I'm having problems with making a list of accounts and storing the info.
This is the class I'm 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 {
// ... (class content)
}
This here below is the JFrame I use to register new accounts. The user enters the info, and when they click 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" loop there only for the purpose of seeing what's happening with the list. It gets the information and prints it 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 {
// ... (class content)
}
This is the class I made to keep the list of accounts and made an add function to add elements to the list:
package banco_projeto;
import java.util.ArrayList;
public class Control {
// ... (class content)
}
I still have a couple of other JFrames, but I'm not sure if they are relevant to my problem. Am I building the list incorrectly? What is happening with my list? Is it because I'm creating the objects inside the methods? Is it working, and I'm just not knowing how to manipulate a list? I tried several different approaches, but nothing changed. If you could provide me with an example of how to fix this, I'll be very grateful.
Thanks in advance!
英文:
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!
答案1
得分: 3
问题:
-
如我在评论中提到的,控件对象不应在监听器内部创建。
-
如果您创建多个 Cadastrar 对象,则控件对象不应在此类内部创建。
-
相反,它应该在非 GUI 模型类中创建,并通过构造函数参数传递到 Cadastrar,设置一个字段。例如:
public class Cadastrar extends javax.swing.JFrame { Control control; public Cadastrar(Control control) { this.control = control; initComponents(); }
-
Cadastrar 不应该是一个 JFrame,而应该是一个 JDialog,可能是一个模态 JDialog。
-
如果是这样,控制类应该控制显示哪个窗口,而不是 Cadastrar。参见:多个 JFrames 的使用:是好还是坏的实践?
在您的评论中,您陈述道:
> 我创建一个,它完成其工作并关闭(使用 dispose();)。然后我再次调用 Cadastrar jframe(从另一个 jframe 的按钮),并创建第二个帐户。我尝试不销毁 Cadastrar jframe,保持它打开,但结果是一样的。我应该显示调用 Cadastrar 的 jframe 吗?
正如我所想的那样 - 每次您创建一个新的 Cadastrar 对象,您都会创建一个新的 Control 对象,之前保存的所有数据都会消失。解决方案就如我上面提到的 - 创建 一个 Control 对象,并在需要的地方传递它。
您的程序设计也不够合理,因为您真的应该考虑将非 GUI 的程序逻辑("模型")与 GUI 部分("视图")分开,并且您不希望向用户显示多个 JFrames,因为这可能会对用户造成很大的困扰。想想您使用过的大多数专业软件,很少会向用户弹出多个窗口。最好通过 CardLayout 切换视图,偶尔使用对话框(JDialog)窗口,而不是多个主程序(JFrame)窗口。应该有一个单独的 JFrame 在整个程序的生命周期内显示。
英文:
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.
答案2
得分: 1
你的问题在这里:
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);
}
每次调用jButtonconfirmarcadastroActionPerformed
方法时,你都创建了一个新的Control
,将当前创建的Conta
添加到其中,然后打印你的列表。
下一次你再创建一个新的并再次打印。
相反地,你应该在方法外部创建control
变量并初始化它。
然后在jButtonconfirmarcadastroActionPerformed
方法中,不要创建一个新的,而是访问在方法外部定义的那个。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论