Advertisement
Guest User

Untitled

a guest
Apr 19th, 2017
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 35.53 KB | None | 0 0
  1. // ===== BancoDAO =====
  2. import java.sql.*; //pacote de classes de manipulação de BD
  3.  
  4. public class BancoDAO {
  5.     //classe connection responsável pela conexão BD
  6.     public static Connection connSistema;
  7.    
  8.     public static void abreConexao() throws Exception{
  9.        
  10.         try{
  11.             //linhas de conexão
  12.             Class.forName("com.mysql.jdbc.Driver");//definindo provedor de banco de dados
  13.            
  14.             //selecionando e abrindo BD(Servidor/Banco, User, Senha)
  15.             connSistema = DriverManager.getConnection("jdbc:mysql://localhost:3306/northwind", "root", "mypass");
  16.         }catch(Exception erro){
  17.             //Disparar mensagem de erro para a classe
  18.             throw new Exception (erro.getMessage());
  19.         }
  20.        
  21.     }
  22.    
  23.     public static void fechaConexao() throws Exception{
  24.        
  25.         try{
  26.             connSistema.close();
  27.         }catch(Exception erro){
  28.             throw new Exception(erro.getMessage());
  29.         }
  30.        
  31.     }
  32.    
  33. }
  34.  
  35. // ===== FECHA BancoDAO =====
  36.  
  37. // ===== ClientesView =====
  38. import javax.swing.*;
  39. import java.awt.*;
  40. import java.awt.event.*;
  41. import javax.swing.event.*;
  42. import javax.swing.table.*;
  43.  
  44.  
  45. public class ClientesView extends JInternalFrame implements ActionListener{
  46.  
  47.     //Declaração dos objetos
  48.    
  49.     public static JMenuBar mbrClientes;
  50.     public static JMenu mnuArquivo, mnuConsultas, mnuAjuda;
  51.     public static JMenuItem mniNovo, mniEditar, mniSalvar, mniExcluir, mniSair;//ARQUIVO
  52.     public static JMenuItem mniConsCod, mniConsNome;//CONSULTA
  53.     public static JMenuItem mniSobre;//AJUDA
  54.            
  55.     public static Container ctnClientes;
  56.     public static String strCampos[] = {"Código: ", "Nome da Empresa: ", "Nome do Representante: ",
  57.                                         "Cargo do Representante: ", "Endereço: ", "Cidade: ", "Estado: ",
  58.                                         "CEP: ", "País: ", "Telefone: ", "E-mail: "};
  59.    
  60.     public static JLabel lblCampos[];
  61.     public static JTextField txtCampos[];
  62.    
  63.     public static String camposTabela[] = {"Código", "Empresa", "Cidade", "Telefone"};
  64.     public static JScrollPane scrClientes;
  65.     public static JTable tblClientes;
  66.     public static DefaultTableModel mdlClientes;
  67.    
  68.     public static JButton btnSalvar, btnEditar, btnAtivar;
  69.    
  70.     public static JLabel lblBusca;
  71.     public static JTextField txtBusca;
  72.     public static JButton btnBusca;
  73.    
  74.     public static ClientesVO objCliente = new ClientesVO();
  75.            
  76.     public static int acao;
  77.    
  78.     public ClientesView(String tmpTitulo){
  79.         super ("NORTHWIND SYSTEM - Módulo " + tmpTitulo);
  80.        
  81.         //Construção dos objetos
  82.        
  83.         mbrClientes = new JMenuBar();
  84.         this.setJMenuBar(mbrClientes);//add barra
  85.        
  86.         mnuArquivo = new JMenu("Arquivo");
  87.         mnuArquivo.setMnemonic('a');//atalho ALT+a
  88.         mbrClientes.add(mnuArquivo);//add na barra
  89.        
  90.         mnuConsultas = new JMenu("Consultas");
  91.         mnuConsultas.setMnemonic('c');//atalho ALT+c
  92.         mbrClientes.add(mnuConsultas);//add na barra
  93.        
  94.         mnuAjuda = new JMenu("Ajuda");
  95.         mnuAjuda.setMnemonic('h');//atalho ALT+h
  96.         mbrClientes.add(mnuAjuda);//add na barra
  97.        
  98.         //Itens do Arquivo
  99.         mniNovo = new JMenuItem("Novo " + tmpTitulo.substring(0,7));
  100.         mniNovo.addActionListener(this);
  101.         mnuArquivo.add(mniNovo);//add no Arquivo
  102.        
  103.         mnuArquivo.add(new JSeparator());
  104.        
  105.         mniEditar = new JMenuItem("Editar " + tmpTitulo.substring(0,7));
  106.         mniEditar.setEnabled(false);
  107.         mniEditar.addActionListener(this);
  108.         mnuArquivo.add(mniEditar);//add no Arquivo
  109.        
  110.         mniSalvar = new JMenuItem("Salvar " + tmpTitulo.substring(0,7));
  111.         mniSalvar.setEnabled(false);
  112.         mniSalvar.addActionListener(this);
  113.         mnuArquivo.add(mniSalvar);//add no Arquivo
  114.        
  115.         mnuArquivo.add(new JSeparator());
  116.        
  117.         mniExcluir = new JMenuItem("Excluir " + tmpTitulo.substring(0,7));
  118.         mniExcluir.addActionListener(this);
  119.         mnuArquivo.add(mniExcluir);//add no Arquivo
  120.        
  121.         mnuArquivo.add(new JSeparator());
  122.        
  123.         mniSair = new JMenuItem("Sair ");
  124.         mniSair.addActionListener(this);
  125.         mnuArquivo.add(mniSair);//add no Arquivo
  126.        
  127.         //Itens do menu Consultas
  128.         mniConsCod = new JMenuItem("Consulta por código ");
  129.         mniConsCod.addActionListener(this);
  130.         mnuConsultas.add(mniConsCod);//add no menu consultas
  131.        
  132.         mniConsNome = new JMenuItem("Consulta por nome ");
  133.         mniConsNome.addActionListener(this);
  134.         mnuConsultas.add(mniConsNome);//add no menu consultas
  135.        
  136.         //Itens do menu Ajuda
  137.         mniSobre = new JMenuItem("Sobre... ");
  138.         mniSobre.addActionListener(this);
  139.         mnuAjuda.add(mniSobre);//add no menu Ajuda
  140.        
  141.         ctnClientes = new Container();
  142.         ctnClientes.setLayout(null);
  143.        
  144.         lblCampos = new JLabel[strCampos.length];
  145.         txtCampos = new JTextField[strCampos.length];
  146.        
  147.         for (int i = 0; i < strCampos.length; i++) {
  148.             lblCampos[i] = new JLabel(strCampos[i]);
  149.             lblCampos[i].setBounds(20, (25*i)+35, 160, 20);
  150.             ctnClientes.add(lblCampos[i]);
  151.            
  152.             txtCampos[i] = new JTextField();
  153.             txtCampos[i].setBounds(180, (25*i)+35, 300, 20);
  154.             ctnClientes.add(txtCampos[i]);
  155.         }
  156.        
  157.         tblClientes = new JTable();
  158.         scrClientes = new JScrollPane(tblClientes);
  159.         mdlClientes = (DefaultTableModel) tblClientes.getModel();
  160.        
  161.         for (int i = 0; i < camposTabela.length; i++) {
  162.             mdlClientes.addColumn(camposTabela[i]);
  163.         }
  164.         //bloqueando campos
  165.         desbloqueiaCampos(false);
  166.         carregarLista();
  167.        
  168.         scrClientes.setBounds(650, 80, 550, 380);
  169.         ctnClientes.add(scrClientes);
  170.        
  171.         btnSalvar = new JButton("SALVAR");
  172.         btnSalvar.setEnabled(false);
  173.         btnSalvar.addActionListener(this);
  174.         btnSalvar.setBounds(500,100,120,120);
  175.         ctnClientes.add(btnSalvar);
  176.        
  177.         btnEditar = new JButton("EDITAR");
  178.         btnEditar.setEnabled(false);
  179.         btnEditar.addActionListener(this);
  180.         btnEditar.setBounds(500,250,120,120);
  181.         ctnClientes.add(btnEditar);
  182.        
  183.         btnAtivar = new JButton("ATIVAR");
  184.         btnAtivar.setVisible(false);
  185.         btnAtivar.addActionListener(this);
  186.         btnAtivar.setBounds(500,60,120,30);
  187.         ctnClientes.add(btnAtivar);
  188.        
  189.         lblBusca = new JLabel("Digite o código");
  190.         lblBusca.setBounds(650,45,120,20);
  191.         ctnClientes.add(lblBusca);
  192.        
  193.         txtBusca = new JTextField("");
  194.         txtBusca.setBounds(760,45,120,20);
  195.         ctnClientes.add(txtBusca);
  196.        
  197.         btnBusca = new JButton("Busca Rápida");
  198.         btnBusca.addActionListener(this);
  199.         btnBusca.setBounds(900,45,120,20);
  200.         ctnClientes.add(btnBusca);
  201.        
  202.         tblClientes.addKeyListener(new KeyAdapter(){
  203.             public void keyReleased(KeyEvent evt){
  204.                 if(evt.getKeyCode() == KeyEvent.VK_DOWN ||
  205.                    evt.getKeyCode() == KeyEvent.VK_UP ||
  206.                    evt.getKeyCode() == KeyEvent.VK_ENTER){
  207.                    
  208.                    try{
  209.                 preencheCampos(ClientesDAO.consultaCliente(1, tblClientes.getValueAt(tblClientes.getSelectedRow(),0).toString()));
  210.                 }catch(Exception erro){
  211.                     JOptionPane.showMessageDialog(null, erro.getMessage());
  212.                 }//catch
  213.                 }
  214.             }
  215.                
  216.         }        
  217.         );
  218.        
  219.         //permite cliques do mouse na lista
  220.         tblClientes.addMouseListener(new MouseAdapter(){
  221.             public void mouseClicked(MouseEvent evt){
  222.                 try{
  223.                 //preencheCampos - recebe como parametro um ClientesVO
  224.                 //consultaClientes - retorna um ClientesVO
  225.                 //ConsultaCliente - requer codigo do cliente como paramentro
  226.                 //codigo do cliente é capturado no momento do clique na tabela
  227.                 preencheCampos(ClientesDAO.consultaCliente(1, tblClientes.getValueAt(tblClientes.getSelectedRow(),0).toString()));
  228.                 }catch(Exception erro){
  229.                     JOptionPane.showMessageDialog(null, erro.getMessage());
  230.                 }
  231.             }
  232.         }
  233.         );
  234.        
  235.         this.addInternalFrameListener(new InternalFrameAdapter(){
  236.            
  237.            public void internalFrameClosing(InternalFrameEvent evt){
  238.                SistemaView.btnMenu[0].setEnabled(true);
  239.            }
  240.         }
  241.         );
  242.        
  243.         this.add(ctnClientes);
  244.         this.setResizable(false);
  245.         this.setClosable(true);
  246.         this.setMaximizable(false);
  247.         this.setIconifiable(true);
  248.         this.setSize(SistemaView.dskJanelas.getWidth(),SistemaView.dskJanelas.getHeight());
  249.         this.show();
  250.        
  251.     }//fechando construtor
  252.    
  253.     public void actionPerformed(ActionEvent evt){
  254.         if(evt.getSource() == btnBusca){
  255.             executaConsulta(txtBusca.getText());
  256.         }
  257.         else if(evt.getSource() == btnSalvar || evt.getSource() == mniSalvar){
  258.            
  259.         if(acao == 1){
  260.             executaCadastro();
  261.         }else if(acao == 2){
  262.             executaAlteracao();
  263.             }
  264.         }
  265.         else if(evt.getSource() == btnAtivar){
  266.             alternaStatus(txtCampos[0].getText());
  267.         }
  268.         else if(evt.getSource() == mniNovo){
  269.             btnAtivar.setVisible(false);
  270.            
  271.             btnEditar.setEnabled(false);
  272.             mniEditar.setEnabled(false);
  273.            
  274.             btnSalvar.setEnabled(true);
  275.             mniSalvar.setEnabled(true);
  276.            
  277.             limparCampos();
  278.            
  279.             desbloqueiaCampos(true);
  280.             acao = 1;
  281.         }
  282.         else if(evt.getSource() == mniEditar || evt.getSource() == btnEditar){
  283.             btnSalvar.setEnabled(true);
  284.             mniSalvar.setEnabled(true);
  285.             desbloqueiaCampos(true);
  286.         }
  287.        
  288.     }//fechando actionperformed
  289.    
  290.     public static void executaCadastro(){
  291.         if(validaCampos()){
  292.                 try{
  293.                 preencheObjeto();//gravando dados das txt no clientesVO
  294.                
  295.                 if(ClientesDAO.consultaCliente(1, objCliente.getCodigo()).getCodigo() != null){
  296.                     JOptionPane.showMessageDialog(null, "Código " + objCliente.getCodigo() + "Já existente");
  297.                 }else{
  298.                 ClientesDAO.cadastraCliente(objCliente);
  299.                 JOptionPane.showMessageDialog((null), "Cliente " + objCliente.getNomeEmpresa() + "Cadastrado com sucesso!");
  300.                 carregarLista();
  301.                 }
  302.                 }catch(Exception erro){
  303.                     JOptionPane.showMessageDialog(null, erro.getMessage());
  304.                 }
  305.             }
  306.     }
  307.    
  308.     public static void executaConsulta(String tmpBusca){
  309.         try{
  310.             objCliente = ClientesDAO.consultaCliente(1, tmpBusca);
  311.            
  312.             if(objCliente.getCodigo() == null){
  313.                 JOptionPane.showMessageDialog(null, "CLIENTE NÃO ENCONTRADO");
  314.             }else{
  315.                 preencheCampos(objCliente);
  316.                
  317.             }
  318.            
  319.         }catch(Exception erro){
  320.             JOptionPane.showMessageDialog(null, erro.getMessage());
  321.         }
  322.     }//fechando executa consulta
  323.    
  324.     public static void executaAlteracao(){
  325.        
  326.         try{
  327.             preencheObjeto();
  328.            
  329.             if(validaCampos()){
  330.                 ClientesDAO.alteraCliente(objCliente, objCliente.getCodigo());
  331.                 JOptionPane.showMessageDialog(null, "Cliente " + objCliente.getCodigo() + " alterado.");
  332.                 desbloqueiaCampos(false);//bloqueando campos
  333.                 carregarLista();//atualizando lista com novos dados
  334.             }
  335.            
  336.         }catch(Exception erro){
  337.             JOptionPane.showMessageDialog(null, erro.getMessage());
  338.         }
  339.     }
  340.            
  341.     public static void desbloqueiaCampos(boolean tmpStatus){
  342.         for (int i = 0; i < txtCampos.length; i++) {
  343.             txtCampos[i].setEditable(tmpStatus);
  344.            
  345.         }
  346.     }
  347.    
  348.     public static void preencheCampos(ClientesVO tmpCliente){
  349.         txtCampos[0].setText(tmpCliente.getCodigo());
  350.         txtCampos[1].setText(tmpCliente.getNomeEmpresa());
  351.         txtCampos[2].setText(tmpCliente.getNomeRepresentante());
  352.         txtCampos[3].setText(tmpCliente.getCargoRepresentante());
  353.         txtCampos[4].setText(tmpCliente.getEndereço());
  354.         txtCampos[5].setText(tmpCliente.getCidade());
  355.         txtCampos[6].setText(tmpCliente.getEstado());
  356.         txtCampos[7].setText(tmpCliente.getCep());
  357.         txtCampos[8].setText(tmpCliente.getPais());
  358.         txtCampos[9].setText(tmpCliente.getTelefone());
  359.         txtCampos[10].setText(tmpCliente.getEmail());
  360.        
  361.         desbloqueiaCampos(false);
  362.        
  363.         btnAtivar.setVisible(true);
  364.        
  365.         mniSalvar.setEnabled(false);
  366.         btnSalvar.setEnabled(false);
  367.        
  368.         mniEditar.setEnabled(true);
  369.         btnEditar.setEnabled(true);
  370.        
  371.         if(tmpCliente.getStatus() == 0){
  372.             txtCampos[1].setForeground(Color.red);
  373.             btnAtivar.setText("Ativar");
  374.         }else{
  375.             txtCampos[1].setForeground(Color.black);
  376.             btnAtivar.setText("Desativar");
  377.         }
  378.        
  379.         acao = 2;
  380.     }
  381.    
  382.     public static void preencheObjeto(){
  383.         objCliente.setCodigo(txtCampos[0].getText());
  384.         objCliente.setNomeEmpresa(txtCampos[1].getText());
  385.         objCliente.setNomeRepresentante(txtCampos[2].getText());
  386.         objCliente.setCargoRepresentante(txtCampos[3].getText());
  387.         objCliente.setEndereço(txtCampos[4].getText());
  388.         objCliente.setCidade(txtCampos[5].getText());
  389.         objCliente.setEstado(txtCampos[6].getText());
  390.         objCliente.setCep(txtCampos[7].getText());
  391.         objCliente.setPais(txtCampos[8].getText());
  392.         objCliente.setTelefone(txtCampos[9].getText());
  393.         objCliente.setEmail(txtCampos[10].getText());
  394.     }
  395.    
  396.     public static void carregarLista(){
  397.         java.util.List<ClientesVO> vetorClientes = new java.util.ArrayList<ClientesVO>();
  398.        
  399.         //Limpar lista
  400.         //enquanto houver elementos na lista
  401.         while(mdlClientes.getRowCount()>0){
  402.             mdlClientes.removeRow(0);//remover o primeiro
  403.         }
  404.        
  405.         try{
  406.             vetorClientes = ClientesDAO.carregaClientes();
  407.            
  408.             //para cada cliente existente no vetor -> cria um objeto clienteVO
  409.             for(ClientesVO tmpCliente: vetorClientes){
  410.                 String dados[] = new String[4];
  411.                     dados[0] = tmpCliente.getCodigo();
  412.                     dados[1] = tmpCliente.getNomeEmpresa();
  413.                     dados[2] = tmpCliente.getCidade();
  414.                     dados[3] = tmpCliente.getTelefone();
  415.                    
  416.                     mdlClientes.addRow(dados);
  417.             }
  418.            
  419.         }catch(Exception erro){
  420.             JOptionPane.showMessageDialog(null, erro.getMessage());
  421.         }
  422.     }
  423.    
  424.     public static boolean validaCampos(){
  425.         //Executando varredura nos campos e verifica qual está vazio
  426.         for(int i=0; i<txtCampos.length; i++){
  427.             if(txtCampos[i].getText().trim().compareTo("") == 0){
  428.                 JOptionPane.showMessageDialog(null, "Preencha o campo " + strCampos[i].toUpperCase());
  429.                 txtCampos[i].grabFocus();//Movendo cursor
  430.                 return false;
  431.             }//fechando if
  432.         }//fechando for
  433.         return true;//Todos os campos preenchidos
  434.     }
  435.    
  436.     public static void alternaStatus(String tmpCodigo){
  437.         try{
  438.             ClientesDAO.alteraStatusCliente((tmpCodigo));
  439.             preencheCampos(ClientesDAO.consultaCliente(1, tmpCodigo));
  440.         }catch(Exception erro){
  441.             JOptionPane.showMessageDialog(null, erro.getMessage());
  442.         }
  443.     }
  444.    
  445.     public static void limparCampos(){
  446.         for (int i = 0; i < txtCampos.length; i++) {
  447.             txtCampos[i].setText(null);
  448.         }
  449.     }
  450. }//fechando class
  451. // ===== FECHA ClientesView  =====
  452.  
  453. // ===== ClientesVO =====
  454. public class ClientesVO {
  455.     //Declaração dos atributos do cliente
  456.    
  457.     public String codigo, nomeEmpresa, nomeRepresentante;
  458.     public String cargoRepresentante, endereço, cidade, estado;
  459.     public String cep, pais, telefone, email;
  460.     public int status;
  461.    
  462.     //Metodo Construtor
  463.     //Vazio - Suporte à construção de um objeto vazio p/ preenchimento dos atributos
  464.     public ClientesVO(){
  465.        
  466.         this.setCodigo(null);
  467.         this.setNomeEmpresa(null);
  468.         this.setNomeRepresentante(null);
  469.         this.setCargoRepresentante(null);
  470.         this.setEndereço(null);
  471.         this.setCidade(null);
  472.         this.setEstado(null);
  473.         this.setCep(null);
  474.         this.setPais(null);
  475.         this.setTelefone(null);
  476.         this.setEmail(null);
  477.         this.setStatus(0);
  478.        
  479.     }
  480.    
  481.     //Metodo Construtor
  482.     //Completo - Suporte à construção de um objeto com os atributos previamente preenchidos
  483.     public ClientesVO(String tmpCodigo, String tmpNomeEmpresa, String tmpNomeRepresentante, String tmpCargoRepresentante, String tmpEndereço, String tmpCidade, String tmpEstado, String tmpCep, String tmpPais, String tmpTelefone, String tmpEmail, int tmpStatus){
  484.        
  485.         this.setCodigo(tmpCodigo);
  486.         this.setNomeEmpresa(tmpNomeEmpresa);
  487.         this.setNomeRepresentante(tmpNomeRepresentante);
  488.         this.setCargoRepresentante(tmpCargoRepresentante);
  489.         this.setEndereço(tmpEndereço);
  490.         this.setCidade(tmpCidade);
  491.         this.setEstado(tmpEstado);
  492.         this.setCep(tmpCep);
  493.         this.setPais(tmpPais);
  494.         this.setTelefone(tmpTelefone);
  495.         this.setEmail(tmpEmail);
  496.         this.setStatus(tmpStatus);
  497.        
  498.     }
  499.  
  500.     //Metodo Construtor
  501.     //Parcial - Suporte à construção de um objeto com os alguns atributos previamente preenchidos
  502.     public ClientesVO(String tmpCodigo, String tmpNomeEmpresa){
  503.        
  504.         this.setCodigo(tmpCodigo);
  505.         this.setNomeEmpresa(tmpNomeEmpresa);
  506.         this.setNomeRepresentante(null);
  507.         this.setCargoRepresentante(null);
  508.         this.setEndereço(null);
  509.         this.setCidade(null);
  510.         this.setEstado(null);
  511.         this.setCep(null);
  512.         this.setPais(null);
  513.         this.setTelefone(null);
  514.         this.setEmail(null);
  515.         this.setStatus(0);
  516.        
  517.     }
  518.    
  519.     //Métodos SET e GET
  520.     public String getCodigo(){
  521.         return this.codigo;
  522.     }
  523.     public void setCodigo(String tmpCodigo){
  524.         this.codigo = tmpCodigo;
  525.     }
  526.    
  527.     public String getNomeEmpresa() {
  528.         return this.nomeEmpresa;
  529.     }
  530.     public void setNomeEmpresa(String tmpNomeEmpresa) {
  531.         this.nomeEmpresa = tmpNomeEmpresa;
  532.     }
  533.  
  534.     public String getNomeRepresentante() {
  535.         return this.nomeRepresentante;
  536.     }
  537.     public void setNomeRepresentante(String tmpNomeRepresentante) {
  538.         this.nomeRepresentante = tmpNomeRepresentante;
  539.     }
  540.  
  541.     public String getCargoRepresentante() {
  542.         return this.cargoRepresentante;
  543.     }
  544.     public void setCargoRepresentante(String tmpCargoRepresentante) {
  545.         this.cargoRepresentante = tmpCargoRepresentante;
  546.     }
  547.  
  548.     public String getEndereço() {
  549.         return this.endereço;
  550.     }
  551.     public void setEndereço(String tmpEndereço) {
  552.         this.endereço = tmpEndereço;
  553.     }
  554.  
  555.     public String getCidade() {
  556.         return this.cidade;
  557.     }
  558.     public void setCidade(String tmpCidade) {
  559.         this.cidade = tmpCidade;
  560.     }
  561.  
  562.     public String getEstado() {
  563.         return this.estado;
  564.     }
  565.     public void setEstado(String tmpEstado) {
  566.         this.estado = tmpEstado;
  567.     }
  568.  
  569.     public String getCep() {
  570.         return this.cep;
  571.     }
  572.     public void setCep(String tmpCep) {
  573.         this.cep = tmpCep;
  574.     }
  575.  
  576.     public String getPais() {
  577.         return this.pais;
  578.     }
  579.     public void setPais(String tmpPais) {
  580.         this.pais = tmpPais;
  581.     }
  582.  
  583.     public String getTelefone() {
  584.         return this.telefone;
  585.     }
  586.     public void setTelefone(String tmpTelefone) {
  587.         this.telefone = tmpTelefone;
  588.     }
  589.  
  590.     public String getEmail() {
  591.         return this.email;
  592.     }
  593.     public void setEmail(String tmpEmail) {
  594.         this.email = tmpEmail;
  595.     }
  596.  
  597.     public int getStatus(){
  598.         return this.status;
  599.     }
  600.     public void setStatus(int tmpStatus){
  601.         this.status = tmpStatus;
  602.     }
  603. }
  604.  
  605. // ===== FECHA ClientesVO  =====
  606.  
  607. // ===== ClientesDAO =====
  608. import java.sql.*;
  609. import java.util.*;
  610.  
  611. public class ClientesDAO {
  612.    
  613.    
  614.    
  615.     //classe Statement permite execução de comandos SQL
  616.     public static Statement stClientes;
  617.    
  618.     //classe ResultSet armazena o resultado de uma instrução Select
  619.     public static ResultSet rsClientes;
  620.    
  621.     public static void cadastraCliente(ClientesVO tmpCliente) throws Exception{
  622.         /*******************ABERTURA DO BANCO DE DADOS*********************/
  623.     try{
  624.         BancoDAO.abreConexao();
  625.      }catch(Exception erro){
  626.          throw new Exception (erro.getMessage());
  627.      }
  628.    
  629.      /************************INSERT*********************/
  630.      try{
  631.          //insert
  632.          String sqlCadastra = "";
  633.          
  634.          sqlCadastra += "INSERT INTO CUSTOMERS(";
  635.          sqlCadastra += "CustomerID, CompanyName,";
  636.          sqlCadastra += "ContactName, ContactTitle,";
  637.          sqlCadastra += "Address, City,";
  638.          sqlCadastra += "Region, PostalCode,";
  639.          sqlCadastra += "Country, Phone,";
  640.          sqlCadastra += "Fax, Status) values (";
  641.          sqlCadastra += "'" + tmpCliente.getCodigo() + "',";
  642.          sqlCadastra += "'" + tmpCliente.getNomeEmpresa() + "',";
  643.          sqlCadastra += "'" + tmpCliente.getNomeRepresentante() + "',";
  644.          sqlCadastra += "'" + tmpCliente.getCargoRepresentante()+ "',";
  645.          sqlCadastra += "'" + tmpCliente.getEndereço()+ "',";
  646.          sqlCadastra += "'" + tmpCliente.getCidade()+ "',";
  647.          sqlCadastra += "'" + tmpCliente.getEstado()+ "',";
  648.          sqlCadastra += "'" + tmpCliente.getCep()+ "',";
  649.          sqlCadastra += "'" + tmpCliente.getPais()+ "',";
  650.          sqlCadastra += "'" + tmpCliente.getTelefone()+ "',";
  651.          sqlCadastra += "'" + tmpCliente.getEmail()+ "',1)";
  652.          
  653.          stClientes = BancoDAO.connSistema.createStatement();
  654.          //utilizado para INSERT, DELETE e UPDATE
  655.          stClientes.executeUpdate(sqlCadastra);
  656.          
  657.          
  658.          
  659.          
  660.      }catch(Exception erro){
  661.         throw new Exception ("FALHA NA INSERÇÃO, VERIFIQUE A SINTAXE DO INSERT.\nErro Original: " + erro.getMessage());
  662.      }
  663.      
  664.      /************************ENCERRAMENTO DO BANCO DE DADOS*********************/
  665.      try{
  666.          BancoDAO.fechaConexao();
  667.      }catch(Exception erro){
  668.          throw new Exception (erro.getMessage());
  669.      }
  670.        
  671.      
  672.     }//fechando cadastraCliente
  673.    
  674.     public static ClientesVO consultaCliente(int tmpTipo, String tmpBusca) throws Exception{
  675.         //Objeto com os dados do cliente que será retornado
  676.         ClientesVO tmpCliente = new ClientesVO();
  677.        
  678.     /*******************ABERTURA DO BANCO DE DADOS*********************/
  679.     try{
  680.         BancoDAO.abreConexao();
  681.      }catch(Exception erro){
  682.          throw new Exception (erro.getMessage());
  683.      }
  684.      /************************EXECUÇÃO SQL*********************/
  685.      try{
  686.          String sqlConsulta = "";
  687.          
  688.          if (tmpTipo == 1){
  689.              //por Código
  690.              sqlConsulta = "SELECT * FROM CUSTOMERS WHERE CustomerID like '" + tmpBusca + "'";
  691.          }else if(tmpTipo == 2){
  692.              //por Nome
  693.              sqlConsulta = "SELECT * FROM CUSTOMERS WHERE CompanyName like '" + tmpBusca + "'";
  694.          }
  695.          
  696.          //executando instrução SELECT e armazenando
  697.          stClientes = BancoDAO.connSistema.createStatement();//ativando statement para o banco selecionado
  698.          rsClientes = stClientes.executeQuery(sqlConsulta);
  699.          
  700.          if(rsClientes.next()){//se houver clientes
  701.              tmpCliente.setCodigo(rsClientes.getString("CustomerID"));
  702.              tmpCliente.setNomeEmpresa(rsClientes.getString("CompanyName"));
  703.              tmpCliente.setNomeRepresentante(rsClientes.getString("ContactName"));
  704.              tmpCliente.setCargoRepresentante(rsClientes.getString("ContactTitle"));
  705.              tmpCliente.setEndereço(rsClientes.getString("Address"));
  706.              tmpCliente.setCidade(rsClientes.getString("City"));
  707.              tmpCliente.setEstado(rsClientes.getString("Region"));
  708.              tmpCliente.setCep(rsClientes.getString("PostalCode"));
  709.              tmpCliente.setPais(rsClientes.getString("Country"));
  710.              tmpCliente.setTelefone(rsClientes.getString("Phone"));
  711.              tmpCliente.setEmail(rsClientes.getString("Fax"));
  712.              tmpCliente.setStatus(rsClientes.getInt("Status"));
  713.          }
  714.          
  715.          //SELECT
  716.      }catch(Exception erro){
  717.          throw new Exception ("FALHA NO SELECT, VERIFIQUE A SINTÁXE DO COMANDO E O NOME DOS CAMPOS/TABELA\nErro Original" + erro.getMessage());
  718.      }
  719.      /************************ENCERRAMENTO DO BANCO DE DADOS*********************/
  720.      try{
  721.          BancoDAO.fechaConexao();
  722.      }catch(Exception erro){
  723.          
  724.      }
  725.        
  726.         return tmpCliente;
  727.     }
  728.    
  729.     public static void excluiCliente(String tmpCodigo) throws Exception{
  730.        
  731.     }
  732.    
  733.     public static void alteraCliente(ClientesVO tmpCliente, String tmpCodigo) throws Exception{
  734.             /*******************ABERTURA DO BANCO DE DADOS*********************/
  735.     try{
  736.         BancoDAO.abreConexao();
  737.      }catch(Exception erro){
  738.          throw new Exception (erro.getMessage());
  739.      }
  740.             /*********************UPDATE****************************/
  741.     try{
  742.        
  743.         String sqlAltera = "";
  744.         sqlAltera += "UPDATE CUSTOMERS set ";
  745.         sqlAltera += "companyName = '" + tmpCliente.getNomeEmpresa() + "',";
  746.         sqlAltera += "contactName = '" + tmpCliente.getNomeRepresentante()+ "',";
  747.         sqlAltera += "contactTitle = '" + tmpCliente.getCargoRepresentante()+ "',";
  748.         sqlAltera += "address = '" + tmpCliente.getEndereço()+ "',";
  749.         sqlAltera += "city = '" + tmpCliente.getCidade()+ "',";
  750.         sqlAltera += "region = '" + tmpCliente.getEstado()+ "',";
  751.         sqlAltera += "country = '" + tmpCliente.getPais()+ "',";
  752.         sqlAltera += "postalCode = '" + tmpCliente.getCep()+ "',";
  753.         sqlAltera += "phone = '" + tmpCliente.getTelefone()+ "',";
  754.         sqlAltera += "fax = '" + tmpCliente.getEmail()+ "' where ";
  755.         sqlAltera += "customerID like '" + tmpCodigo + "'";
  756.        
  757.         stClientes = BancoDAO.connSistema.createStatement();
  758.         stClientes.executeUpdate(sqlAltera);
  759.        
  760.        
  761.      }catch(Exception erro){
  762.         throw new Exception ("Falha no Update. Verifique a sintaxe." + "\nErro Original: " + erro.getMessage());
  763.      }
  764.    
  765.              /******************ENCERRAMENTO DO BANCO DE DADOS*********************/
  766.     try{
  767.          BancoDAO.fechaConexao();
  768.      }catch(Exception erro){
  769.          throw new Exception (erro.getMessage());
  770.      }
  771.     }
  772.    
  773.     public static void alteraStatusCliente(String tmpCodigo) throws Exception{
  774.         ClientesVO tmpCliente = new ClientesVO();
  775.      /*******************ABERTURA DO BANCO DE DADOS*********************/
  776.         try{
  777.         BancoDAO.abreConexao();
  778.      }catch(Exception erro){
  779.          throw new Exception (erro.getMessage());
  780.      }
  781.      /************************EXECUÇÃO SQL*********************/
  782.      try{
  783.          tmpCliente = consultaCliente(1, tmpCodigo);
  784.          BancoDAO.abreConexao();
  785.          
  786.          int novoStatus;
  787.          if(tmpCliente.getStatus() == 0){
  788.              novoStatus = 1;
  789.          }else{
  790.              novoStatus = 0;
  791.          }
  792.          //update status
  793.          String sqlStatus = "Update customers set status = " + novoStatus + " where customerid like '" + tmpCodigo + "'";
  794.          stClientes = BancoDAO.connSistema.createStatement();
  795.          stClientes.executeUpdate(sqlStatus);
  796.      }catch(Exception erro){
  797.          throw new Exception ("FALHA NA ALTERAÇÃO, VERIFIQUE INSTRUÇÃO UPDATE\nErro Original" + erro.getMessage());
  798.      }
  799.      /************************ENCERRAMENTO DO BANCO DE DADOS*********************/
  800.      try{
  801.          BancoDAO.fechaConexao();
  802.      }catch(Exception erro){
  803.          
  804.      }
  805.     }
  806.    
  807.     public static List<ClientesVO> carregaClientes() throws Exception{
  808.         //declarando e instanciando vetor de ClientesVO
  809.        
  810.         List<ClientesVO> vetorClientes = new ArrayList<ClientesVO>();
  811.        
  812.         try{
  813.             BancoDAO.abreConexao();
  814.         }catch(Exception erro){
  815.             throw new Exception(erro.getMessage());
  816.         }
  817.        
  818.         //EXECUÇÃO DO SELECT
  819.         try{
  820.         String sqlClientes = "Select * from CUSTOMERS";
  821.        
  822.         stClientes = BancoDAO.connSistema.createStatement();
  823.         rsClientes = stClientes.executeQuery(sqlClientes);
  824.            
  825.         //enquanto houver clientes na tabela
  826.         while(rsClientes.next()){
  827.             ClientesVO clienteAtual = new ClientesVO();
  828.             clienteAtual.setCodigo(rsClientes.getString("CustomerID"));
  829.             clienteAtual.setNomeEmpresa(rsClientes.getString("CompanyName"));
  830.             clienteAtual.setCidade(rsClientes.getString("City"));
  831.             clienteAtual.setTelefone(rsClientes.getString("Phone"));
  832.            
  833.             //add clienteAtual ao vetor
  834.             vetorClientes.add(clienteAtual);
  835.         }
  836.        
  837.         }catch(Exception erro){
  838.             throw new Exception("Falha no carregamento da lista.\nErro original: " + erro.getMessage());
  839.         }
  840.                
  841.         try{
  842.             BancoDAO.fechaConexao();
  843.         }catch(Exception erro){
  844.             throw new Exception(erro.getMessage());
  845.         }
  846.        
  847.         return vetorClientes;
  848.    
  849.     }//fechando carregaClientes
  850. }
  851.  
  852. // ===== FECHA ClientesDAO  =====
  853.  
  854. // ===== SistemaControl =====
  855. //Projeto NorthwindSystem
  856. public class SistemaControl {
  857.  
  858.     public static void main(String[] args) {
  859.         TelaView ObjTela = new TelaView();
  860.     }
  861.    
  862. }
  863.  
  864. // ===== FECHA SistemaControl   =====
  865.  
  866. // ===== SistemaView =====
  867. import javax.swing.*;
  868. import java.awt.*;
  869. import java.awt.event.*;
  870.  
  871. public class SistemaView extends JFrame implements ActionListener {
  872.    
  873.     //Declaração dos objetos
  874.     public static Container ctnPrincipal, ctnTopo, ctnMenu;
  875.     public static JLabel lblBanner;
  876.     public static JButton btnMenu[];
  877.     public static String modulos[] = {"CLIENTES", "FUNCIONÁRIOS", "FORNECEDOR", "PRODUTOS",
  878.                             "VENDAS", "CAIXA", "USUÁRIOS", "SAIR"};
  879.     public static JDesktopPane dskJanelas;
  880.        
  881.     public SistemaView(){
  882.         super("Northwind System - Sistema Gerenciador de Vendas");
  883.        
  884.         //Construção dos objetos
  885.         ctnPrincipal = new Container();
  886.         ctnPrincipal.setLayout(new BorderLayout());
  887.        
  888.         ctnTopo = new Container();
  889.         ctnTopo.setLayout(new GridLayout(2,1));
  890.        
  891.         ctnMenu = new Container();
  892.         ctnMenu.setLayout(new GridLayout(2,4));
  893.        
  894.         lblBanner = new JLabel(new ImageIcon("img/banner.jpg"));
  895.        
  896.        
  897.        
  898.         btnMenu = new JButton[8];
  899.         for(int i=0; i<btnMenu.length; i++){
  900.             btnMenu[i] = new JButton(new ImageIcon("img/" + i + ".jpg"));
  901.             btnMenu[i].addActionListener(this);
  902.             btnMenu[i].setToolTipText(modulos[i]);//'dica' do botão
  903.             ctnMenu.add(btnMenu[i]);
  904.         }
  905.        
  906.         //Objeto que permite abertura de janelas internas
  907.         dskJanelas = new JDesktopPane();
  908.        
  909.         //Adicionando objetos na janela
  910.         this.add(ctnPrincipal); //add principal na janela
  911.        
  912.         ctnPrincipal.add(ctnTopo, BorderLayout.NORTH);//add topo no norte do principal
  913.        
  914.         ctnTopo.add(lblBanner);//add banner na primeira célula do topo
  915.         ctnTopo.add(ctnMenu);//add banner na segunda linha do topo
  916.        
  917.         ctnPrincipal.add(dskJanelas, BorderLayout.CENTER);//add desktop no centro do principal
  918.        
  919.         //chamando fechar janela ao clica no X do JFrame
  920.         this.addWindowListener(new WindowAdapter() {
  921.             public void windowClosing(WindowEvent evt){
  922.                 if(!fecharJanela()){
  923.                     setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
  924.                 }else{
  925.                     System.exit(0);
  926.                 }
  927.             }
  928.         }
  929.         );
  930.        
  931.         this.setSize(montarTela());
  932.         this.show();
  933.         //Encerra o processo ao fechar a janela
  934.         this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  935.     }//fechando Construtor
  936.    
  937.     public static Dimension montarTela(){
  938.         Toolkit info = Toolkit.getDefaultToolkit();
  939.         Dimension res = info.getScreenSize();
  940.        
  941.         return res;
  942.     }
  943.    
  944.     public void actionPerformed(ActionEvent evt){
  945.         if(evt.getSource() == btnMenu[0]){
  946.             dskJanelas.add(new ClientesView(modulos[0]));
  947.             btnMenu[0].setEnabled(false);
  948.         }
  949.        
  950.        
  951.         if (evt.getSource() == btnMenu[7]){
  952.             if(fecharJanela())
  953.             System.exit(0);
  954.         }
  955.     }//Fechando ActionPerformed
  956.    
  957.     public static boolean fecharJanela(){
  958.         int resp = JOptionPane.showConfirmDialog(null, "Deseja encerrar o sistema?", "SAIR", JOptionPane.YES_NO_OPTION);
  959.        
  960.         if(resp == JOptionPane.YES_OPTION)
  961.             return true;
  962.         else
  963.             return false;
  964.     }
  965. }
  966.  
  967. // ===== FECHA SistemaView  =====
  968.  
  969. // ===== TelaView =====
  970. import java.awt.*;
  971. import javax.swing.*;
  972.  
  973. public class TelaView extends JFrame {
  974.    
  975.     //Variaveis de coordenadas da abertura da janela
  976.     public static int xFinal, yFinal;
  977.    
  978.     public TelaView(){
  979.         int largTela = 640, altTela = 480;
  980.        
  981.         Container ctnTela = new Container();
  982.         ctnTela.setLayout(null);
  983.        
  984.         JLabel lblFundo = new JLabel(new ImageIcon("img/imgFundo.png"));
  985.        
  986.         this.add(ctnTela);
  987.         lblFundo.setBounds(0, 0, largTela, altTela);
  988.         ctnTela.add(lblFundo);
  989.        
  990.         centralizar(largTela, altTela);
  991.        
  992.         this.setLocation(xFinal, yFinal);
  993.         this.setUndecorated(true);//Tira as bordas da janela
  994.         this.setSize(largTela,altTela);
  995.        
  996.         try{
  997.             this.show();//exibindo
  998.             Thread.sleep(1000);//aguardando
  999.             this.dispose();//encerrando
  1000.            
  1001.             //abrindo telaPrincipal
  1002.             SistemaView objTelaSistema = new SistemaView();
  1003.            
  1004.         }catch(Exception erro){
  1005.            
  1006.     }
  1007.        
  1008.        
  1009.     }//Fim construtor
  1010.    
  1011.     public static void centralizar(int tmpLarg, int tmpAlt){
  1012.         Toolkit info = Toolkit.getDefaultToolkit();
  1013.         Dimension dim = info.getScreenSize();
  1014.        
  1015.         xFinal = (int) (dim.getWidth()/2) - (tmpLarg/2);
  1016.         yFinal = (int) (dim.getHeight()/2) - (tmpAlt/2);
  1017.     }
  1018.    
  1019. }
  1020.  
  1021. // ===== FECHA TelaView  =====
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement