Estou fazendo um pequeno CRUD com o tema poupança para fins de estudo. Criei 3 classes: Poupanca, Contas e Tela (UI Swing).
Na tela eu efetuo o cadastro de uma conta com os atributos nome, agência, número de conta (o saldo inicia com valor 0 por padrão), conforme o construtor.
O problema: não consigo recuperar os dados nos métodos consultar ou remover conta por exemplo. Ou retorna o próprio nome inserido na UI na hora da pesquisa ou não retorna nada.
O que eu preciso: Digitar o atributo nome do titular de uma conta Poupanca(objeto) e pelo nome o sistema fazer uma busca no ArrayList contas. Se encontrar o nome, retornar o objeto (a conta) que tem esse nome como atributo (e apresentar os dados dessa conta na TextArea), caso contrário retornar nulo.
obs: o método consultar 2 é outra tentativa de consulta. Mas acredito que o erro está na classe main (Tela.java). Tenho a impressão que tem algo errado nos métodos dos botões, mas não consegui resolver. Tentei criar o objeto no escopo da classe, tentei criar direto no escopo dos métodos dos botões, etc...nada da certo.
Classe 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;
}
}
Classe Contas.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() + "";
}
}
Classe Tela.java completa:
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
}