Olá, estou desenvolvendo meu TCC e estou tendo problemas com o Try… Catch… tentei resolver, porém está dando erro n SQLException e ClassNotFoundExcpetion…
Classe Clientes
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Model;
import conexao.BancoSql;
import java.sql.SQLException;
import java.util.Date;
/**
*
* @author Carol
*/
public class Clientes {
//Declarando os atributos(variáveis)
private String nome;
private int codigo;
private String endereco;
private String telefone;
private String pdtComprado;
private String totCompraMes;
private Date dtPagamento;
private Date dtCompra;
//Gerando o Getters and Setters
public Date getDtCompra() {
return dtCompra;
}
public void setDtCompra(Date dtCompra) {
this.dtCompra = dtCompra;
}
public Date getDtPagamento() {
return dtPagamento;
}
public void setDtPagamento(Date dtPagamento) {
this.dtPagamento = dtPagamento;
}
public String getPdtComprado() {
return pdtComprado;
}
public void setPdtComprado(String pdtComprado) {
this.pdtComprado = pdtComprado;
}
public String getTotCompraMes() {
return totCompraMes;
}
public void setTotCompraMes(String totCompraMes) {
this.totCompraMes = totCompraMes;
}
public double getValCompra() {
return valCompra;
}
public void setValCompra(double valCompra) {
this.valCompra = valCompra;
}
private double valCompra;
public int getCodigo() {
return codigo;
}
public void setCodigo(int codigo) {
this.codigo = codigo;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
//Declarando os métodos para incluir, alterar e escluir.
public void incluir() throws SQLException, ClassNotFoundException{
throw new UnsupportedOperationException("Not supported yet.");
}
public void alterar() throws SQLException, ClassNotFoundException{
throw new UnsupportedOperationException("Not supported yet.");
}
public void excluir() throws SQLException, ClassNotFoundException{
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* @return the nome
*/
}
Classe ClientesDAO
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package DAO;
/**
*
* @author Carol
*/
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import Model.Clientes;
import conexao.BancoSql;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
public class ClientesDAO extends Clientes {
private Connection conexao;
private PreparedStatement comandoSQL;
private Date dataPag;
private ArrayList<Clientes> listaClientes;
public Date getDataCompra() {
return dataCompra;
}
public void setDataCompra(Date dataCompra) {
this.dataCompra = dataCompra;
}
public Date getDataPag() {
return dataPag;
}
public void setDataPag(Date dataPag) {
this.dataPag = dataPag;
}
private Date dataCompra;
/*
* Classe responsável pela interação da aplicação com o banco de dados
*/
Clientes cli = new Clientes();
// Driver de conexao ao MySql
private String servidor = "com.mysql.jdbc.Driver";
// url que identifica o banco
private String urlBanco = "jdbc:mysql://localhost:3306/aula";
// login de usuario no banco
private String usuarioBanco = "root";
// senha do usuario no banco
private String senhaBanco = "root";
public void incluir() throws SQLException, ClassNotFoundException {
//set dateformat dmy
String sql = "INSERT INTO Clientes("
+ "codigo, nome, endereco,"
+ "telefone, pdtComprado,totCompraMes"
+ "dtPagamento, dtCompra) VALUES"
+ "(?,?,?,?,?,?,?,?)";
//Usando o método estático criado em BancoSql
this.conexao = BancoSql.getConnection();
comandoSQL = conexao.prepareStatement(sql);
comandoSQL.setInt(1, this.getCodigo());
comandoSQL.setString(2, this.getNome());
comandoSQL.setString(3, this.getEndereco());
comandoSQL.setString(4, this.getTelefone());
comandoSQL.setString(5, this.getPdtComprado());
comandoSQL.setString(6, this.getTotCompraMes());
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
dataPag = new Date(getDtPagamento().getTime());
comandoSQL.setString(7, sdf.format(dataPag));
dataCompra = new Date(getDtCompra().getTime());
comandoSQL.setString(8, sdf.format(dataCompra));
comandoSQL.execute();
comandoSQL.close();
this.conexao.close();
//Usando o método estático criado em BancoSql
this.conexao = BancoSql.getConnection();
}
@Override
public void alterar() throws SQLException, ClassNotFoundException {
String sql = "UPDATE Clientes SET"
+ "nome=?"
+ "codigo=?"
+ "endereco=?"
+ "telefone=?"
+ "pdtComprado=?"
+ "totCompraMes=?"
+ "dtPagamento=?"
+ "dtCompra=?"
+ "WHERE Clientes = ?";
this.conexao = BancoSql.getConnection();
comandoSQL = conexao.prepareStatement(sql);
comandoSQL.setString(1, this.getNome());
comandoSQL.setString(2, this.getEndereco());
comandoSQL.setString(3, this.getTelefone());
comandoSQL.setString(4, this.getPdtComprado());
comandoSQL.setString(5, this.getTotCompraMes());
dataPag = new Date(this.getDtPagamento().getTime());
comandoSQL.setDate(6, dataPag);
dataCompra = new Date(this.getDtCompra().getTime());
comandoSQL.setDate(7, dataCompra);
comandoSQL.setInt(8, this.getCodigo());
comandoSQL.execute();
comandoSQL.close();
this.conexao.close();
}
@Override
public void excluir() throws ClassNotFoundException {
String sql = "DELETE FROM Clientes"
+ " where codigo = ?";
try {
this.conexao = BancoSql.getConnection();
comandoSQL.setInt(1, this.getCodigo());
comandoSQL.execute();
comandoSQL.close();
this.conexao.close();
} catch (Exception ex) {
try {
throw ex;
} catch (Exception ex1) {
Logger.getLogger(ClientesDAO.class.getName()).log(Level.SEVERE, null, ex1);
}
// } catch (ClassNotFoundException ex) {
// throw ex;
}
}
public ArrayList<Clientes> pesquisar(Clientes cli) {
throw new UnsupportedOperationException("Not yet implemented");
}
}
Formulário GerenCli
/*ESTE É O FORMULÁRIO DE GERENCIAMENTO DE CLIENTES(CADASTRO, CONSULTA, ALTERAÇÃO
* E EXCLUSÃO) QUE CONTERÁ UMA TABELA PARA A FACILITAÇÃO DE GERENCIAMENTO
* CRIADA NO DIA 02/11/2011, 14:24:37
*/
package Interface;//PACOTE INTERFACE QUE CONTEM OS FORMULÁRIOS QUE FAZEM A
//INTERFACE ENTRE O USUÁRIO E O BANCO DE DADOS
import DAO.ClientesDAO;
import Model.Clientes;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.text.DefaultFormatterFactory;
import javax.swing.text.MaskFormatter;
/**
* @author Carol
*/
public class GerenCli extends javax.swing.JDialog {
Clientes cli = new Clientes();
ClientesDAO cliDao = new ClientesDAO();
MaskFormatter mfTel;
MaskFormatter mfDataCompra;
MaskFormatter mfDataPag;
boolean gravar = false;
boolean editar = false;
private int posLinha;
/** CRIAÇÃO DO FORMULÁRIO GerenCli */
public GerenCli(java.awt.Frame parent, boolean modal) {
super(parent, modal);
try {
mfTel = new MaskFormatter("(##)####-####");
mfTel.setPlaceholderCharacter('-');
//mfTel.setValidCharacters("1234567");
mfTel.setValueContainsLiteralCharacters(false);
mfTel.setValueClass(String.class);
DefaultFormatterFactory dffTel = new DefaultFormatterFactory(mfTel);
tfTelefone.setFormatterFactory(dffTel);
mfDataCompra = new MaskFormatter("##/##/####");
mfDataCompra.setPlaceholderCharacter('-');
mfDataCompra.setValueContainsLiteralCharacters(true);
mfDataCompra.setValueClass(String.class);
DefaultFormatterFactory dffDtCompra = new DefaultFormatterFactory(mfDataCompra);
tfDtCompra.setFormatterFactory(dffDtCompra);
mfDataPag = new MaskFormatter("##/##/####");
mfDataPag.setPlaceholderCharacter('-');
mfDataPag.setValueContainsLiteralCharacters(true);
mfDataPag.setValueClass(String.class);
DefaultFormatterFactory dffDtPag = new DefaultFormatterFactory(mfDataPag);
tfDtPagamento.setFormatterFactory(dffDtPag);
} catch (ParseException e) {
}
initComponents();
setTitle("Gerenciar Cliente"); // TITULO DA TELA
}
private void habilitaBotoes(boolean hab) {
btnIncluir.setEnabled(hab);
btnAlterar.setEnabled(hab);
btnExcluir.setEnabled(hab);
btnConsultar.setEnabled(hab);
btnGravar.setEnabled(hab);
btnCancelar.setEnabled(hab);
}
private void habilitaCampos(boolean hab) {
tfCodigo.setEnabled(hab);
tfNome.setEnabled(hab);
tfEndereco.setEnabled(hab);
tfTotCompraMes.setEnabled(hab);
tfTelefone.setEnabled(hab);
tfDtCompra.setEnabled(hab);
tfDtPagamento.setEnabled(hab);
}
private void limpaCampos() {
tfCodigo.setText("");
tfNome.setText("");
tfEndereco.setText("");
tfTotCompraMes.setText("");
//OS CAMPOS ABAIXO SAO JFORMATTEDTEXTFIELD, POR ISSO USAREMOS SETCALUE()
tfTelefone.setValue("");
tfDtCompra.setValue("");
tfDtPagamento.setValue("");
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
pGerenCli = new javax.swing.JPanel();
pGerenCliCadastrar = new javax.swing.JPanel();
lblNome = new javax.swing.JLabel();
lblEndereco = new javax.swing.JLabel();
lblTelefone = new javax.swing.JLabel();
btnIncluir = new javax.swing.JButton();
btnCancelar = new javax.swing.JButton();
tfNome = new javax.swing.JTextField();
tfEndereco = new javax.swing.JTextField();
lblCodigo = new javax.swing.JLabel();
tfCodigo = new javax.swing.JTextField();
btnAlterar = new javax.swing.JButton();
btnConsultar = new javax.swing.JButton();
btnExcluir = new javax.swing.JButton();
lblPdtComprado = new javax.swing.JLabel();
jScrollPane1 = new javax.swing.JScrollPane();
listPdtComprado = new javax.swing.JList();
lblTotCompraMes = new javax.swing.JLabel();
tfTotCompraMes = new javax.swing.JTextField();
btnGravar = new javax.swing.JButton();
lblDtPagamento = new javax.swing.JLabel();
tfDtPagamento = new javax.swing.JFormattedTextField();
lblDtCompra = new javax.swing.JLabel();
tfDtCompra = new javax.swing.JFormattedTextField();
tfTelefone = new javax.swing.JFormattedTextField();
scrollPtblGerenCli = new javax.swing.JScrollPane();
tblGerenCli = new javax.swing.JTable();
setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
pGerenCli.setBackground(new java.awt.Color(204, 204, 204));
pGerenCli.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
pGerenCliCadastrar.setBackground(new java.awt.Color(204, 204, 204));
pGerenCliCadastrar.setBorder(javax.swing.BorderFactory.createTitledBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED), "Cadastrar"));
lblNome.setText("Nome:");
lblEndereco.setText("Endereco:");
lblTelefone.setText("Telefone:");
btnIncluir.setText("Incluir");
btnIncluir.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
btnIncluir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnIncluirActionPerformed(evt);
}
});
btnCancelar.setText("Cancelar");
btnCancelar.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
btnCancelar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelarActionPerformed(evt);
}
});
tfNome.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tfNomeActionPerformed(evt);
}
});
tfEndereco.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tfEnderecoActionPerformed(evt);
}
});
lblCodigo.setText("Codigo:");
tfCodigo.setEditable(false);
tfCodigo.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tfCodigoActionPerformed(evt);
}
});
btnAlterar.setText("Alterar");
btnAlterar.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
btnAlterar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnAlterarActionPerformed(evt);
}
});
btnConsultar.setText("Consultar");
btnConsultar.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
btnConsultar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnConsultarActionPerformed(evt);
}
});
btnExcluir.setText("Excluir");
btnExcluir.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
btnExcluir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnExcluirActionPerformed(evt);
}
});
lblPdtComprado.setText("Produtos Comprados:");
listPdtComprado.setModel(new javax.swing.AbstractListModel() {
String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
public int getSize() { return strings.length; }
public Object getElementAt(int i) { return strings[i]; }
});
jScrollPane1.setViewportView(listPdtComprado);
lblTotCompraMes.setText("Total de Compra ao mes:");
tfTotCompraMes.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
tfTotCompraMesActionPerformed(evt);
}
});
btnGravar.setText("Gravar");
btnGravar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnGravarActionPerformed(evt);
}
});
lblDtPagamento.setText("Data de Pagamento:");
lblDtCompra.setText("Data de Compra:");
javax.swing.GroupLayout pGerenCliCadastrarLayout = new javax.swing.GroupLayout(pGerenCliCadastrar);
pGerenCliCadastrar.setLayout(pGerenCliCadastrarLayout);
pGerenCliCadastrarLayout.setHorizontalGroup(
pGerenCliCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pGerenCliCadastrarLayout.createSequentialGroup()
.addGroup(pGerenCliCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pGerenCliCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(pGerenCliCadastrarLayout.createSequentialGroup()
.addComponent(lblCodigo)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 70, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(pGerenCliCadastrarLayout.createSequentialGroup()
.addComponent(lblNome)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(tfNome))
.addGroup(pGerenCliCadastrarLayout.createSequentialGroup()
.addComponent(lblEndereco)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, 298, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(pGerenCliCadastrarLayout.createSequentialGroup()
.addComponent(lblTelefone)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 146, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(pGerenCliCadastrarLayout.createSequentialGroup()
.addComponent(lblTotCompraMes)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfTotCompraMes, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(pGerenCliCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pGerenCliCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pGerenCliCadastrarLayout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 46, Short.MAX_VALUE)
.addComponent(btnIncluir, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnAlterar, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnConsultar, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
.addGroup(pGerenCliCadastrarLayout.createSequentialGroup()
.addGap(16, 16, 16)
.addComponent(lblDtPagamento)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfDtPagamento, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(33, 33, 33)))
.addGroup(pGerenCliCadastrarLayout.createSequentialGroup()
.addGap(18, 18, 18)
.addComponent(lblDtCompra)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(tfDtCompra, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)))
.addGroup(pGerenCliCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pGerenCliCadastrarLayout.createSequentialGroup()
.addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 52, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(btnGravar)
.addGap(32, 32, 32)
.addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 63, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(pGerenCliCadastrarLayout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(lblPdtComprado)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(112, 112, 112))
);
pGerenCliCadastrarLayout.setVerticalGroup(
pGerenCliCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pGerenCliCadastrarLayout.createSequentialGroup()
.addGroup(pGerenCliCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblCodigo)
.addComponent(tfCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnCancelar)
.addComponent(btnExcluir, javax.swing.GroupLayout.PREFERRED_SIZE, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnConsultar)
.addComponent(btnAlterar)
.addComponent(btnIncluir)
.addComponent(btnGravar))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addGroup(pGerenCliCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pGerenCliCadastrarLayout.createSequentialGroup()
.addGroup(pGerenCliCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblNome)
.addComponent(tfNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(lblDtPagamento)
.addComponent(tfDtPagamento, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pGerenCliCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pGerenCliCadastrarLayout.createSequentialGroup()
.addGroup(pGerenCliCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblEndereco)
.addComponent(tfEndereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pGerenCliCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tfTelefone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pGerenCliCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblTotCompraMes, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(tfTotCompraMes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(pGerenCliCadastrarLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(lblDtCompra)
.addComponent(tfDtCompra, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(pGerenCliCadastrarLayout.createSequentialGroup()
.addComponent(lblPdtComprado, javax.swing.GroupLayout.PREFERRED_SIZE, 12, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(38, 38, 38))
.addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE))
.addContainerGap())
);
tblGerenCli.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null, null, null}
},
new String [] {
"Codigo", "Nome", "Endereco", "Telefone"
}
) {
Class[] types = new Class [] {
java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class
};
boolean[] canEdit = new boolean [] {
false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types [columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit [columnIndex];
}
});
scrollPtblGerenCli.setViewportView(tblGerenCli);
javax.swing.GroupLayout pGerenCliLayout = new javax.swing.GroupLayout(pGerenCli);
pGerenCli.setLayout(pGerenCliLayout);
pGerenCliLayout.setHorizontalGroup(
pGerenCliLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pGerenCliLayout.createSequentialGroup()
.addGroup(pGerenCliLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, pGerenCliLayout.createSequentialGroup()
.addGap(20, 20, 20)
.addComponent(scrollPtblGerenCli))
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, pGerenCliLayout.createSequentialGroup()
.addContainerGap()
.addComponent(pGerenCliCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pGerenCliLayout.setVerticalGroup(
pGerenCliLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pGerenCliLayout.createSequentialGroup()
.addContainerGap()
.addComponent(pGerenCliCadastrar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(scrollPtblGerenCli, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE)
.addContainerGap())
);
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pGerenCli, 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(pGerenCli, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
);
pack();
}// </editor-fold>
private void tfNomeActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void tfEnderecoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnIncluirActionPerformed(java.awt.event.ActionEvent evt) {
habilitaBotoes(false);
habilitaCampos(true);
limpaCampos();
tfCodigo.requestFocus();
gravar = true;
}
private void tfCodigoActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnConsultarActionPerformed(java.awt.event.ActionEvent evt) {
ClientesDAO c = new ClientesDAO();
Clientes cli = new Clientes();
String nome = JOptionPane.showInputDialog(null, "Infome o nome do cliente ou parte dele: ",
"Pesquisa: ", JOptionPane.QUESTION_MESSAGE);
cli.setNome(nome);
try {
ArrayList<Clientes> ListaClientes = c.pesquisar(cli);
atualizaTable(ListaClientes);
/* } catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Ocoreeu um erro no BD: " + e.getMessage(),
"Erro: ", JOptionPane.ERROR_MESSAGE);
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, "Ocorreu um erro de classe: " + e.getMessage(),
"Erro: ", JOptionPane.ERROR_MESSAGE);
*/ } catch (Exception e) {
JOptionPane.showMessageDialog(null, "Ocorreu um erro: " + e.getMessage(),
"Erro: ", JOptionPane.ERROR_MESSAGE);
}
}
private void btnExcluirActionPerformed(java.awt.event.ActionEvent evt) {
try {
//Receber o código do cliente a ser apagado
int Codigo = Integer.valueOf(JOptionPane.showInputDialog(null,
"Informe o código do cliente que deseja excluir:",
"Código do cliente", JOptionPane.QUESTION_MESSAGE));
ClientesDAO cd = new ClientesDAO();
cd.setCodigo(Codigo);
cd.excluir();
formWindowOpened(null);
} catch (NumberFormatException e) {
JOptionPane.showMessageDialog(null, "Ocorreu um erro: " + e.getMessage(),
"Erro: ", JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Ocorreu um erro:" + e.getMessage(),
"Erro: ", JOptionPane.ERROR_MESSAGE);
}
}
private void tfTotCompraMesActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
}
private void btnGravarActionPerformed(java.awt.event.ActionEvent evt) {
try {
//Novo DaoClientes para armazenar os dados que serão Gravados/Alterados
DAO.ClientesDAO dcli = new DAO.ClientesDAO();
//o sdf declarado abaixo será usado para converter a data de
//String para Date
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
//Preenchendo o dcli (DaoClientes)com os dados
dcli.setCodigo(Integer.valueOf(tfCodigo.getText()));
dcli.setNome(tfNome.getText());
dcli.setEndereco(tfEndereco.getText());
dcli.setTotCompraMes(tfTotCompraMes.getText());
dcli.setTelefone(tfTelefone.getValue().toString());
dcli.setDtCompra(sdf.parse(tfDtCompra.getText()));
dcli.setDtCompra(sdf.parse(tfDtPagamento.getText()));
dcli.setDtPagamento(sdf.parse(tfDtCompra.getText()));
dcli.setDtPagamento(sdf.parse(tfDtPagamento.getText()));
//caso o usuario escolheu incluir
if (gravar) {
dcli.incluir();
}
//caso o usuario escolheu alterar
if (editar) {
dcli.alterar();
}
//Voltando o formulário para o padrão
habilitaBotoes(true);
habilitaCampos(false);
gravar = false;
editar = false;
limpaCampos();
//Atualizando o Jtable
formWindowOpened(null);
//Tratando possíveis exceções
} catch (SQLException s) {
JOptionPane.showMessageDialog(null, "Ocorreu um erro no"
+ "Canco de dados:" = s.getMessage(),
"Erro:", JOptionPane.ERROR_MESSAGE);
} catch (ClassNotFoundException c) {
JOptionPane.showMessageDialog(null, "Ocorreu um erro ao"
+ "Carregar o driver do BD: " + c.getMessage(),
"Erro: ", JOptionPane.ERROR_MESSAGE);
} catch (ParseException p) {
JOptionPane.showMessageDialog(null, "Ocorreu um erro de"
+ "conversão: " + p.getMessage(),
"Erro: ", JOptionPane.ERROR_MESSAGE);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, "Ocorreu um erro"
+ ex.getMessage(),
"Erro: ", JOptionPane.ERROR_MESSAGE);
}
}/*
try { //Novo DaoClientes para armazenar os dados que serão Gravados/Alterados Model.banco.DAOClientes dcli = new Model.banco.DAOClientes(); //o sdf declarado abaixo será usado para converter a data de //String para Date SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy"); //Preenchendo o dcli (DaoClientes)com os dados dcli.setCodCli(Integer.valueOf(tfCodigo.getText())); dcli.setNome(tfNome.getText()); dcli.setEndereco(tfEndereco.getText()); dcli.setCidade(tfCidade.getText()); dcli.setBairro(tfBairro.getText()); dcli.setUf(tfUf.getValue().toString()); dcli.setCep(tfCep.getValue().toString()); dcli.setTelefone(tfTelefone.getValue().toString()); dcli.setDataNasc(sdf.parse(tfNascimento.getText())); //caso o usuario escolheu incluir if (gravar) { dcli.incluir(); } //caso o usuario escolheu alterar if (editar) { dcli.alterar(); } //Voltando o formulário para o padrão habilitaBotoes(true); habilitaCampos(false); gravar = false; editar = false; limpaCampos(); //Atualizando o Jtable formWindowOpened(null); //Tratando possíveis exceções } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Ocorreu um erro no" + "Canco de dados:" = e.getMessage(), "Erro:", JOptionPane.ERROR_MESSAGE); } catch (ClassNotFoundException e) { JOptionPane.showMessageDialog(null, "Ocorreu um erro ao" + "Carregar o driver do BD: " + e.getMessage(), "Erro: ", JOptionPane.ERROR_MESSAGE); } catch (ParseException e) { JOptionPane.showMessageDialog(null, "Ocorreu um erro de" + "conversão: " + e.getMessage(), "Erro: ", JOptionPane.ERROR_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(null, "Ocorreu um erro" + e.getMessage(), "Erro: ", JOptionPane.ERROR_MESSAGE); } }
*/
private void btnAlterarActionPerformed(java.awt.event.ActionEvent evt) {
habilitaBotoes(false);
habilitaCampos(true);
limpaCampos();
tfCodigo.setEnabled(false);
tfNome.requestFocus();
editar = true;
try {
//Verifica se tem clientes no grid
if (tblGerenCli.getRowCount() > 0) {
//linha selecionada no JTable
int posLinha = tblGerenCli.getSelectedRow();
//verificar se a linha foi selecionada, caso 'true' pega
//os dados da respectiva linha e envi para os campos
if (posLinha >= 0) {
tfCodigo.setText(tblGerenCli.getValueAt(posLinha, 0).toString());
tfNome.setText(tblGerenCli.getValueAt(posLinha, 1).toString());
tfEndereco.setText(tblGerenCli.getValueAt(posLinha, 2).toString());
listPdtComprado.setText(tblGerenCli.getValueAt(posLinha, 3).toString());
tfTotCompraMes.setText(tblGerenCli.getValueAt(posLinha, 4).toString());
//Verificando se o campo Telefone no JTable está vazio
if (tblGerenCli.getValueAt(posLinha, 5).toString().equals("(__)____-____")) {
tfTelefone.setValue("");
} else {
try {
//Usamos o MasFomatter abaixo para converter de
//"textoParaValor" <--> atringToValue o dado do telefone, pois
//ele esá formatado pelo mesmo
tfTelefone.setValue(mfTel.stringToValue(
tblGerenCli.getValueAt(posLinha, 5).toString()).toString());
} catch (ParseException ex) {
Logger.getLogger(GerenCli.class.getName()).log(Level.SEVERE, null, ex);
}
}
tfDtPagamento.setValue(tblGerenCli.getValueAt(posLinha, 6).toString());
}
tfDtCompra.setValue(tblGerenCli.getValueAt(posLinha, 6).toString());
}
else
{
JOptionPane.showMessageDialog(null, "Selecione um cliente para alterar!",
"Erro: ", JOptionPane.ERROR_MESSAGE);
btnCancelarActionPerformed(null);
}
else
{
JOptionPane.showMessageDialog(null, "Não há clientes cadastrados ainda!",
"Erro: ", JOptionPane.ERROR_MESSAGE);
btnCancelarActionPerformed(null);
}
catch
(Exception e) {
JOptionPane.showMessageDialog(null, "Ocorreu um erro " + e.getMessage(),
"Erro: ", JOptionPane.ERROR_MESSAGE);
}
private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
habilitaBotoes(true);
habilitaCampos(false);
limpaCampos();
gravar = false;
editar = false;
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
//Carregando os dados na inicialização do formulário.
//Modo similar ao do btnPesquisar
ClientesDAO c = new ClientesDAO();
Clientes cli = new Clientes();
cli.setNome("");
ArrayList<Clientes> ListaClientes;
try {
ListaClientes = c.pesquisar(cli);
atualizaTable(ListaClientes);
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Ocorreu um erro no BD: " + e.getMessage(),
"Erro: ", JOptionPane.ERROR_MESSAGE);
} catch (ClassNotFoundException e) {
JOptionPane.showMessageDialog(null, "Ocorreu um erro de classe: " + e.getMessage(),
"Erro: ", JOptionPane.ERROR_MESSAGE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Ocorreu um erro: " + e.getMessage(),
"Erro: ", JOptionPane.ERROR_MESSAGE);
}
}
private void atualizaTable(ArrayList<Clientes> clientes) {
//Objeto para formatar Datas
SimpleDateFormat sdf = new SimpleDateFormat("dd/mm/yyyy");
if (clientes.isEmpty()) {
JOptionPane.showMessageDialog(null, "Não foram encontrados clientes"
+ "no banco de dados.",
"Atenção: ", JOptionPane.INFORMATION_MESSAGE);
} else {
//Modelo de Tabela para popular tblCadClientes (JTable)
DefaultTableModel dadosClientes = new DefaultTableModel(null,
new String[]{"Código", "Nome", "Endereço", "Cidade", "Beirro",
"UF", "Cep", "Telefone", "Data de Nascimento"});
String Linha[] = new String[]{"", "", "", "", "", "", "", "", ""};
try {
//Criado como referencia para posição da linha
int posicao = 1;
for (Iterator<Clientes> it = clientes.iterator().it.hasNext(); ) {
Clientes cliente = it.next();
posicao++;
//incluindo linha em branco
dadosClientes.addRow(Linha);
//preenchendo a linha em branco, celula a celula
dadosClientes.setValueAt(cliente.getCodigo(), posicao, 0);
dadosClientes.setValueAt(cliente.getNome(), posicao, 1);
dadosClientes.setValueAt(cliente.getEndereco(), posicao, 2);
dadosClientes.setValueAt(cliente.getTotCompraMes(), posicao, 3);
dadosClientes.setValueAt(cliente.getValCompra(), posicao, 4);
//Usando o MaskFormatter para formatar o dado do campo Telefone
dadosClientes.setValueAt(mfTel.valueToString(cliente.getTelefone()), posicao, 6);
//Usando o SimpleDateFormat para formatar o dado do campo DataNasc
dadosClientes.setValueAt(sdf.format(cliente.getDtCompra().getTime()), posicao, 7);
dadosClientes.setValueAt(sdf.format(cliente.getDtPagamento().getTime()), posicao, 7);
}
//Populando tblCadClientes (JTable) com dadosClientes já preenchida
tblGerenCli.setModel(dadosClientes);
}catch (Exception e){
JOptionPane.showMessageDialog(null, "Ocorreu um erro: " + e.getMessage(),
"Erro: ", JOptionPane.ERROR_MESSAGE);
}
}
}
//CRIAÇÃO DOS COMPONENTES(BOTÕES, TEXT FIELDS, RÓTULOS, TABELAS, PAINÉIS E ETC)
// Variables declaration - do not modify
private javax.swing.JButton btnAlterar;
private javax.swing.JButton btnCancelar;
private javax.swing.JButton btnConsultar;
private javax.swing.JButton btnExcluir;
private javax.swing.JButton btnGravar;
private javax.swing.JButton btnIncluir;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JLabel lblCodigo;
private javax.swing.JLabel lblDtCompra;
private javax.swing.JLabel lblDtPagamento;
private javax.swing.JLabel lblEndereco;
private javax.swing.JLabel lblNome;
private javax.swing.JLabel lblPdtComprado;
private javax.swing.JLabel lblTelefone;
private javax.swing.JLabel lblTotCompraMes;
private javax.swing.JList listPdtComprado;
private javax.swing.JPanel pGerenCli;
private javax.swing.JPanel pGerenCliCadastrar;
private javax.swing.JScrollPane scrollPtblGerenCli;
private javax.swing.JTable tblGerenCli;
private javax.swing.JTextField tfCodigo;
private javax.swing.JFormattedTextField tfDtCompra;
private javax.swing.JFormattedTextField tfDtPagamento;
private javax.swing.JTextField tfEndereco;
private javax.swing.JTextField tfNome;
private javax.swing.JFormattedTextField tfTelefone;
private javax.swing.JTextField tfTotCompraMes;
// End of variables declaration
}
Aradeço a atenção!