segunda-feira, 28 de abril de 2008

Aplicação MDI Simples - 4.a Parte

1.a e 2.a Parte - Aqui
3.a Parte - Aqui

A 4.a parte do post é sobre a codificação classe CadClientes responsavel pelas operações de incluir/excluir/editar/consultar da janela clientes.

OBS: Todos os metodos apresentados nesta classe foram desenvolvidos para serem apresentados da maneira mais simples possivel, mesmo que funcional não traz tratamento de erros, excessões nem os metodos mais corretos existentes, como informado anteriormente e vale ressaltar que tutorial foi feito somente para incentivar e instigar os leitores (aprendizes assim como eu) ao estudo e pesquisa para um melhor aperfeiçoamento.

Segue codificação da classe CadClientes:



import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDesktopPane;
import javax.swing.JFormattedTextField;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import javax.swing.JTextField;
import javax.swing.SwingConstants;
import javax.swing.text.MaskFormatter;

public class CadClientes extends JInternalFrame implements ActionListener {

JTextField tfCodigo,
tfNome,
tfLog,
tfBairro,
tfCidade;

JFormattedTextField tfRG,
tfCPF,
tfDataNasc,
tfFone,
tfCel;

JComboBox cbUF;

String [] UF = { "AC","AL","AM","AP","BA","CE","DF","ES","GO","MA","MG","MS",
"MT","PA","PB","PE","PI","PR","RJ","RN","RO","RR","RS","SC",
"SE","SP","TO" };

JSeparator linha;

Conexao conexao = new Conexao();
String status;

public CadClientes(){
super("Loja MDI - Cadastro de Clientes", true, true, false, true);
setSize(600, 320);
setResizable(false);
setLayout(null);

JLabel label = new JLabel("Código");
label.setBounds(20, 10, 60, 20);
add(label);

tfCodigo = new JTextField();
tfCodigo.setBounds(80, 10, 80, 20);
add(tfCodigo);

linha = new JSeparator();
linha.setOrientation(SwingConstants.HORIZONTAL);
linha.setBounds(10, 45, 570, 20);
add(linha);

label = new JLabel("Nome");
label.setBounds(20, 60, 60, 20);
add(label);

tfNome = new JTextField();
tfNome.setBounds(80, 60, 500, 20);
add(tfNome);

label = new JLabel("Logradouro");
label.setBounds(20, 90, 80, 20);
add(label);

tfLog = new JTextField();
tfLog.setBounds(110, 90, 240, 20);
add(tfLog);

label = new JLabel("Bairro");
label.setBounds(370, 90, 60, 20);
add(label);

tfBairro = new JTextField();
tfBairro.setBounds(420, 90, 150, 20);
add(tfBairro);

label = new JLabel("Cidade");
label.setBounds(20, 120, 60, 20);
add(label);

tfCidade = new JTextField();
tfCidade.setBounds(80, 120, 240, 20);
add(tfCidade);

label = new JLabel("Estado");
label.setBounds(340, 120, 60, 20);
add(label);

cbUF = new JComboBox(UF);
cbUF.setMaximumRowCount(4);
cbUF.setBounds(395, 120, 50, 20);
add(cbUF);

label = new JLabel("RG");
label.setBounds(20, 150, 40, 20);
add(label);

tfRG = new JFormattedTextField(formatRG());
// acerto de bug do formattedtextfield
tfRG.setFocusLostBehavior(JFormattedTextField.PERSIST);
tfRG.setBounds(60, 150, 120, 20);
add(tfRG);

label = new JLabel("CPF");
label.setBounds(200, 150, 40, 20);
add(label);

tfCPF = new JFormattedTextField(formatCPF());
tfCPF.setFocusLostBehavior(JFormattedTextField.PERSIST);
tfCPF.setBounds(240, 150, 120, 20);
add(tfCPF);

label = new JLabel("Data de Nasc.");
label.setBounds(380, 150, 100, 20);
add(label);

tfDataNasc = new JFormattedTextField(formatData());
tfDataNasc.setFocusLostBehavior(JFormattedTextField.PERSIST);
tfDataNasc.setBounds(470, 150, 100, 20);
add(tfDataNasc);

label = new JLabel("Fone Res.");
label.setBounds(20, 180, 80, 20);
add(label);

tfFone = new JFormattedTextField(formatFone());
tfFone.setFocusLostBehavior(JFormattedTextField.PERSIST);
tfFone.setBounds(100, 180, 120, 20);
add(tfFone);

label = new JLabel("Fone Cel.");
label.setBounds(250, 180, 80, 20);
add(label);

tfCel = new JFormattedTextField(formatFone());
tfCel.setFocusLostBehavior(JFormattedTextField.PERSIST);
tfCel.setBounds(320, 180, 120, 20);
add(tfCel);

linha = new JSeparator();
linha.setOrientation(SwingConstants.HORIZONTAL);
linha.setBounds(10, 220, 570, 20);
add(linha);

JButton button = new JButton("Inserir");
button.setMnemonic(KeyEvent.VK_I);
button.setActionCommand("inserir");
button.addActionListener(this);
button.setBounds(25, 245, 100, 20);
add(button);

button = new JButton("Excluir");
button.setMnemonic(KeyEvent.VK_E);
button.setActionCommand("excluir");
button.addActionListener(this);
button.setBounds(135, 245, 100, 20);
add(button);

button = new JButton("Editar");
button.setMnemonic(KeyEvent.VK_E);
button.setActionCommand("editar");
button.addActionListener(this);
button.setBounds(245, 245, 100, 20);
add(button);

button = new JButton("Consultar");
button.setMnemonic(KeyEvent.VK_C);
button.setActionCommand("consultar");
button.addActionListener(this);
button.setBounds(355, 245, 100, 20);
add(button);

button = new JButton("Sair");
button.setMnemonic(KeyEvent.VK_S);
button.setActionCommand("sair");
button.addActionListener(this);
button.setBounds(465, 245, 100, 20);
add(button);

centralizar(LojaMDI.desktopPane);
setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);
setVisible(true);
}

public static MaskFormatter formatRG(){
MaskFormatter date = new MaskFormatter();

try{
date.setMask("##.###.###-#");
date.setPlaceholderCharacter('_');
}
catch(ParseException exc){
exc.printStackTrace();
}
return date;
}

public static MaskFormatter formatCPF(){
MaskFormatter date = new MaskFormatter();

try{
date.setMask("###.###.###-##");
date.setPlaceholderCharacter('_');
}
catch(ParseException exc){
exc.printStackTrace();
}
return date;
}

public static MaskFormatter formatData(){
MaskFormatter date = new MaskFormatter();

try{
date.setMask("##/##/####");
date.setPlaceholderCharacter('_');
}
catch(ParseException exc){
exc.printStackTrace();
}
return date;
}

public static MaskFormatter formatFone(){
MaskFormatter date = new MaskFormatter();

try{
date.setMask("(##)####-####");
date.setPlaceholderCharacter('_');
}
catch(ParseException exc){
exc.printStackTrace();
}
return date;
}

public void centralizar(JDesktopPane dp) {
Dimension ds = dp.getSize();
Dimension dw = this.getSize();
this.setLocation((ds.width - dw.width) / 2, (ds.height - dw.height) / 2);
}

public String inserir(){
status = "Método não inicializado.";
try{
conexao.abrirConexao();
Statement stmt = conexao.con.createStatement();
String query = "insert into clientes values (" + tfCodigo.getText()
+ ",'" + tfNome.getText()
+ "','" + tfLog.getText()
+ "','" + tfBairro.getText()
+ "','" + tfCidade.getText()
+ "','" + cbUF.getSelectedItem()
+ "','" + tfRG.getText()
+ "','" + tfCPF.getText()
+ "','" + tfDataNasc.getText()
+ "','" + tfFone.getText()
+ "','" + tfCel.getText()+ "');";
int resultado = stmt.executeUpdate(query);
if(resultado == 1){
status = "Dados Inseridos com sucesso.";
}
else{
status = "Dados não inseridos.";
}
conexao.fecharConexao();
stmt.close();
}
catch(SQLException excIns){
excIns.printStackTrace();
}
return status;
}

public void consultar() {

String cons = JOptionPane.showInputDialog(null,"Digite o código do cliente");
DateFormat data = new SimpleDateFormat("ddMMyyyy");

try{
conexao.abrirConexao();
Statement stmt = conexao.con.createStatement();

ResultSet rsCons = stmt.executeQuery("select * from clientes where " +
"cod_cli = "+cons+";");

while(rsCons.next()){
tfCodigo.setText(rsCons.getString("cod_cli"));
tfNome.setText(rsCons.getString("nom_cli"));
tfLog.setText(rsCons.getString("log"));
tfBairro.setText(rsCons.getString("bairro"));
tfCidade.setText(rsCons.getString("cidade"));
if(rsCons.getString("uf").equals("AC")){
cbUF.setSelectedIndex(0);
}
if(rsCons.getString("uf").equals("AL")){
cbUF.setSelectedIndex(1);
}
if(rsCons.getString("uf").equals("AM")){
cbUF.setSelectedIndex(2);
}
if(rsCons.getString("uf").equals("AP")){
cbUF.setSelectedIndex(3);
}
if(rsCons.getString("uf").equals("BA")){
cbUF.setSelectedIndex(4);
}
if(rsCons.getString("uf").equals("CE")){
cbUF.setSelectedIndex(5);
}
if(rsCons.getString("uf").equals("DF")){
cbUF.setSelectedIndex(6);
}
if(rsCons.getString("uf").equals("ES")){
cbUF.setSelectedIndex(7);
}
if(rsCons.getString("uf").equals("GO")){
cbUF.setSelectedIndex(8);
}
if(rsCons.getString("uf").equals("MA")){
cbUF.setSelectedIndex(9);
}
if(rsCons.getString("uf").equals("MG")){
cbUF.setSelectedIndex(10);
}
if(rsCons.getString("uf").equals("MS")){
cbUF.setSelectedIndex(11);
}
if(rsCons.getString("uf").equals("MT")){
cbUF.setSelectedIndex(12);
}
if(rsCons.getString("uf").equals("PA")){
cbUF.setSelectedIndex(13);
}
if(rsCons.getString("uf").equals("PB")){
cbUF.setSelectedIndex(14);
}
if(rsCons.getString("uf").equals("PE")){
cbUF.setSelectedIndex(15);
}
if(rsCons.getString("uf").equals("PI")){
cbUF.setSelectedIndex(16);
}
if(rsCons.getString("uf").equals("PR")){
cbUF.setSelectedIndex(17);
}
if(rsCons.getString("uf").equals("RJ")){
cbUF.setSelectedIndex(18);
}
if(rsCons.getString("uf").equals("RN")){
cbUF.setSelectedIndex(19);
}
if(rsCons.getString("uf").equals("RO")){
cbUF.setSelectedIndex(20);
}
if(rsCons.getString("uf").equals("RR")){
cbUF.setSelectedIndex(21);
}
if(rsCons.getString("uf").equals("RS")){
cbUF.setSelectedIndex(22);
}
if(rsCons.getString("uf").equals("SC")){
cbUF.setSelectedIndex(23);
}
if(rsCons.getString("uf").equals("SE")){
cbUF.setSelectedIndex(24);
}
if(rsCons.getString("uf").equals("SP")){
cbUF.setSelectedIndex(25);
}
if(rsCons.getString("uf").equals("TO")){
cbUF.setSelectedIndex(26);
}
tfRG.setText(rsCons.getString("rg"));
tfCPF.setText(rsCons.getString("cpf"));
tfDataNasc.setText(data.format(rsCons.getDate("dt_nasc")));
tfFone.setText(rsCons.getString("fone"));
tfCel.setText(rsCons.getString("cel"));
}
stmt.close();
conexao.fecharConexao();
}
catch(SQLException excCon){
excCon.printStackTrace();
}
}

public void deletar(){
try{
conexao.abrirConexao();
Statement stmt = conexao.con.createStatement();

Object [] simNao = { "Sim", "Não" };

int opcao = JOptionPane.showOptionDialog(null, "Deseja excluir este registro ?",
"Loja MDI", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
simNao, simNao[0]);
if(opcao == JOptionPane.YES_OPTION){
stmt.executeUpdate("delete from clientes where cod_cli = " +
tfCodigo.getText() + ";");
}
stmt.close();
conexao.fecharConexao();
}
catch(SQLException excCon){
excCon.printStackTrace();
}
}

public void atualizar(){
try{
conexao.abrirConexao();
Statement stmt = conexao.con.createStatement();

Object [] simNao = { "Sim", "Não" };

int opcao = JOptionPane.showOptionDialog(null, "Deseja atualiza este registro ?",
"Loja MDI", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
simNao, simNao[0]);
if(opcao == JOptionPane.YES_OPTION){
stmt.executeUpdate("update clientes set nom_cli = '" + tfNome.getText()
+ "', log = '" + tfLog.getText()
+ "', bairro = '" + tfBairro.getText()
+ "', cidade = '" + tfCidade.getText()
+ "', uf = '" + cbUF.getSelectedItem()
+ "', rg = '" + tfRG.getText()
+ "', cpf = '" + tfCPF.getText()
+ "', dt_nasc = '" + tfDataNasc.getText()
+ "', fone = '" + tfFone.getText()
+ "', cel = '" + tfCel.getText()
+ "' where cod_cli = " + tfCodigo.getText() + ";");
}
stmt.close();
conexao.fecharConexao();
}
catch(SQLException excCon){
excCon.printStackTrace();
}
}

public void limpaForm(){
tfCodigo.setText("");
tfNome.setText("");
tfLog.setText("");
tfBairro.setText("");
tfCidade.setText("");
cbUF.setSelectedIndex(0);
tfRG.setText("");
tfCPF.setText("");
tfDataNasc.setText("");
tfFone.setText("");
tfCel.setText("");
}

public void actionPerformed(ActionEvent e) {
if("inserir".equals(e.getActionCommand())){
this.inserir();
this.limpaForm();
JOptionPane.showMessageDialog(null, status,
"Loja MDI - Cadastro de Cliente",
JOptionPane.INFORMATION_MESSAGE);
}

if("consultar".equals(e.getActionCommand())){
this.consultar();
}

if("editar".equals(e.getActionCommand())){
this.atualizar();
this.limpaForm();
}

if("excluir".equals(e.getActionCommand())){
this.deletar();
this.limpaForm();
}

if("sair".equals(e.getActionCommand())){
dispose();
}
}
}


:: Referências

GUJ
Java Free
Oraculo

Um comentário:

Anônimo disse...

Excelente iniciativa! Realmente, me foi muito útil! Aguardo pelas proximas etapas! Muito Obrigado!