Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // ===== BancoDAO =====
- import java.sql.*; //pacote de classes de manipulação de BD
- public class BancoDAO {
- //classe connection responsável pela conexão BD
- public static Connection connSistema;
- public static void abreConexao() throws Exception{
- try{
- //linhas de conexão
- Class.forName("com.mysql.jdbc.Driver");//definindo provedor de banco de dados
- //selecionando e abrindo BD(Servidor/Banco, User, Senha)
- connSistema = DriverManager.getConnection("jdbc:mysql://localhost:3306/northwind", "root", "mypass");
- }catch(Exception erro){
- //Disparar mensagem de erro para a classe
- throw new Exception (erro.getMessage());
- }
- }
- public static void fechaConexao() throws Exception{
- try{
- connSistema.close();
- }catch(Exception erro){
- throw new Exception(erro.getMessage());
- }
- }
- }
- // ===== FECHA BancoDAO =====
- // ===== ClientesView =====
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- import javax.swing.event.*;
- import javax.swing.table.*;
- public class ClientesView extends JInternalFrame implements ActionListener{
- //Declaração dos objetos
- public static JMenuBar mbrClientes;
- public static JMenu mnuArquivo, mnuConsultas, mnuAjuda;
- public static JMenuItem mniNovo, mniEditar, mniSalvar, mniExcluir, mniSair;//ARQUIVO
- public static JMenuItem mniConsCod, mniConsNome;//CONSULTA
- public static JMenuItem mniSobre;//AJUDA
- public static Container ctnClientes;
- public static String strCampos[] = {"Código: ", "Nome da Empresa: ", "Nome do Representante: ",
- "Cargo do Representante: ", "Endereço: ", "Cidade: ", "Estado: ",
- "CEP: ", "País: ", "Telefone: ", "E-mail: "};
- public static JLabel lblCampos[];
- public static JTextField txtCampos[];
- public static String camposTabela[] = {"Código", "Empresa", "Cidade", "Telefone"};
- public static JScrollPane scrClientes;
- public static JTable tblClientes;
- public static DefaultTableModel mdlClientes;
- public static JButton btnSalvar, btnEditar, btnAtivar;
- public static JLabel lblBusca;
- public static JTextField txtBusca;
- public static JButton btnBusca;
- public static ClientesVO objCliente = new ClientesVO();
- public static int acao;
- public ClientesView(String tmpTitulo){
- super ("NORTHWIND SYSTEM - Módulo " + tmpTitulo);
- //Construção dos objetos
- mbrClientes = new JMenuBar();
- this.setJMenuBar(mbrClientes);//add barra
- mnuArquivo = new JMenu("Arquivo");
- mnuArquivo.setMnemonic('a');//atalho ALT+a
- mbrClientes.add(mnuArquivo);//add na barra
- mnuConsultas = new JMenu("Consultas");
- mnuConsultas.setMnemonic('c');//atalho ALT+c
- mbrClientes.add(mnuConsultas);//add na barra
- mnuAjuda = new JMenu("Ajuda");
- mnuAjuda.setMnemonic('h');//atalho ALT+h
- mbrClientes.add(mnuAjuda);//add na barra
- //Itens do Arquivo
- mniNovo = new JMenuItem("Novo " + tmpTitulo.substring(0,7));
- mniNovo.addActionListener(this);
- mnuArquivo.add(mniNovo);//add no Arquivo
- mnuArquivo.add(new JSeparator());
- mniEditar = new JMenuItem("Editar " + tmpTitulo.substring(0,7));
- mniEditar.setEnabled(false);
- mniEditar.addActionListener(this);
- mnuArquivo.add(mniEditar);//add no Arquivo
- mniSalvar = new JMenuItem("Salvar " + tmpTitulo.substring(0,7));
- mniSalvar.setEnabled(false);
- mniSalvar.addActionListener(this);
- mnuArquivo.add(mniSalvar);//add no Arquivo
- mnuArquivo.add(new JSeparator());
- mniExcluir = new JMenuItem("Excluir " + tmpTitulo.substring(0,7));
- mniExcluir.addActionListener(this);
- mnuArquivo.add(mniExcluir);//add no Arquivo
- mnuArquivo.add(new JSeparator());
- mniSair = new JMenuItem("Sair ");
- mniSair.addActionListener(this);
- mnuArquivo.add(mniSair);//add no Arquivo
- //Itens do menu Consultas
- mniConsCod = new JMenuItem("Consulta por código ");
- mniConsCod.addActionListener(this);
- mnuConsultas.add(mniConsCod);//add no menu consultas
- mniConsNome = new JMenuItem("Consulta por nome ");
- mniConsNome.addActionListener(this);
- mnuConsultas.add(mniConsNome);//add no menu consultas
- //Itens do menu Ajuda
- mniSobre = new JMenuItem("Sobre... ");
- mniSobre.addActionListener(this);
- mnuAjuda.add(mniSobre);//add no menu Ajuda
- ctnClientes = new Container();
- ctnClientes.setLayout(null);
- lblCampos = new JLabel[strCampos.length];
- txtCampos = new JTextField[strCampos.length];
- for (int i = 0; i < strCampos.length; i++) {
- lblCampos[i] = new JLabel(strCampos[i]);
- lblCampos[i].setBounds(20, (25*i)+35, 160, 20);
- ctnClientes.add(lblCampos[i]);
- txtCampos[i] = new JTextField();
- txtCampos[i].setBounds(180, (25*i)+35, 300, 20);
- ctnClientes.add(txtCampos[i]);
- }
- tblClientes = new JTable();
- scrClientes = new JScrollPane(tblClientes);
- mdlClientes = (DefaultTableModel) tblClientes.getModel();
- for (int i = 0; i < camposTabela.length; i++) {
- mdlClientes.addColumn(camposTabela[i]);
- }
- //bloqueando campos
- desbloqueiaCampos(false);
- carregarLista();
- scrClientes.setBounds(650, 80, 550, 380);
- ctnClientes.add(scrClientes);
- btnSalvar = new JButton("SALVAR");
- btnSalvar.setEnabled(false);
- btnSalvar.addActionListener(this);
- btnSalvar.setBounds(500,100,120,120);
- ctnClientes.add(btnSalvar);
- btnEditar = new JButton("EDITAR");
- btnEditar.setEnabled(false);
- btnEditar.addActionListener(this);
- btnEditar.setBounds(500,250,120,120);
- ctnClientes.add(btnEditar);
- btnAtivar = new JButton("ATIVAR");
- btnAtivar.setVisible(false);
- btnAtivar.addActionListener(this);
- btnAtivar.setBounds(500,60,120,30);
- ctnClientes.add(btnAtivar);
- lblBusca = new JLabel("Digite o código");
- lblBusca.setBounds(650,45,120,20);
- ctnClientes.add(lblBusca);
- txtBusca = new JTextField("");
- txtBusca.setBounds(760,45,120,20);
- ctnClientes.add(txtBusca);
- btnBusca = new JButton("Busca Rápida");
- btnBusca.addActionListener(this);
- btnBusca.setBounds(900,45,120,20);
- ctnClientes.add(btnBusca);
- tblClientes.addKeyListener(new KeyAdapter(){
- public void keyReleased(KeyEvent evt){
- if(evt.getKeyCode() == KeyEvent.VK_DOWN ||
- evt.getKeyCode() == KeyEvent.VK_UP ||
- evt.getKeyCode() == KeyEvent.VK_ENTER){
- try{
- preencheCampos(ClientesDAO.consultaCliente(1, tblClientes.getValueAt(tblClientes.getSelectedRow(),0).toString()));
- }catch(Exception erro){
- JOptionPane.showMessageDialog(null, erro.getMessage());
- }//catch
- }
- }
- }
- );
- //permite cliques do mouse na lista
- tblClientes.addMouseListener(new MouseAdapter(){
- public void mouseClicked(MouseEvent evt){
- try{
- //preencheCampos - recebe como parametro um ClientesVO
- //consultaClientes - retorna um ClientesVO
- //ConsultaCliente - requer codigo do cliente como paramentro
- //codigo do cliente é capturado no momento do clique na tabela
- preencheCampos(ClientesDAO.consultaCliente(1, tblClientes.getValueAt(tblClientes.getSelectedRow(),0).toString()));
- }catch(Exception erro){
- JOptionPane.showMessageDialog(null, erro.getMessage());
- }
- }
- }
- );
- this.addInternalFrameListener(new InternalFrameAdapter(){
- public void internalFrameClosing(InternalFrameEvent evt){
- SistemaView.btnMenu[0].setEnabled(true);
- }
- }
- );
- this.add(ctnClientes);
- this.setResizable(false);
- this.setClosable(true);
- this.setMaximizable(false);
- this.setIconifiable(true);
- this.setSize(SistemaView.dskJanelas.getWidth(),SistemaView.dskJanelas.getHeight());
- this.show();
- }//fechando construtor
- public void actionPerformed(ActionEvent evt){
- if(evt.getSource() == btnBusca){
- executaConsulta(txtBusca.getText());
- }
- else if(evt.getSource() == btnSalvar || evt.getSource() == mniSalvar){
- if(acao == 1){
- executaCadastro();
- }else if(acao == 2){
- executaAlteracao();
- }
- }
- else if(evt.getSource() == btnAtivar){
- alternaStatus(txtCampos[0].getText());
- }
- else if(evt.getSource() == mniNovo){
- btnAtivar.setVisible(false);
- btnEditar.setEnabled(false);
- mniEditar.setEnabled(false);
- btnSalvar.setEnabled(true);
- mniSalvar.setEnabled(true);
- limparCampos();
- desbloqueiaCampos(true);
- acao = 1;
- }
- else if(evt.getSource() == mniEditar || evt.getSource() == btnEditar){
- btnSalvar.setEnabled(true);
- mniSalvar.setEnabled(true);
- desbloqueiaCampos(true);
- }
- }//fechando actionperformed
- public static void executaCadastro(){
- if(validaCampos()){
- try{
- preencheObjeto();//gravando dados das txt no clientesVO
- if(ClientesDAO.consultaCliente(1, objCliente.getCodigo()).getCodigo() != null){
- JOptionPane.showMessageDialog(null, "Código " + objCliente.getCodigo() + "Já existente");
- }else{
- ClientesDAO.cadastraCliente(objCliente);
- JOptionPane.showMessageDialog((null), "Cliente " + objCliente.getNomeEmpresa() + "Cadastrado com sucesso!");
- carregarLista();
- }
- }catch(Exception erro){
- JOptionPane.showMessageDialog(null, erro.getMessage());
- }
- }
- }
- public static void executaConsulta(String tmpBusca){
- try{
- objCliente = ClientesDAO.consultaCliente(1, tmpBusca);
- if(objCliente.getCodigo() == null){
- JOptionPane.showMessageDialog(null, "CLIENTE NÃO ENCONTRADO");
- }else{
- preencheCampos(objCliente);
- }
- }catch(Exception erro){
- JOptionPane.showMessageDialog(null, erro.getMessage());
- }
- }//fechando executa consulta
- public static void executaAlteracao(){
- try{
- preencheObjeto();
- if(validaCampos()){
- ClientesDAO.alteraCliente(objCliente, objCliente.getCodigo());
- JOptionPane.showMessageDialog(null, "Cliente " + objCliente.getCodigo() + " alterado.");
- desbloqueiaCampos(false);//bloqueando campos
- carregarLista();//atualizando lista com novos dados
- }
- }catch(Exception erro){
- JOptionPane.showMessageDialog(null, erro.getMessage());
- }
- }
- public static void desbloqueiaCampos(boolean tmpStatus){
- for (int i = 0; i < txtCampos.length; i++) {
- txtCampos[i].setEditable(tmpStatus);
- }
- }
- public static void preencheCampos(ClientesVO tmpCliente){
- txtCampos[0].setText(tmpCliente.getCodigo());
- txtCampos[1].setText(tmpCliente.getNomeEmpresa());
- txtCampos[2].setText(tmpCliente.getNomeRepresentante());
- txtCampos[3].setText(tmpCliente.getCargoRepresentante());
- txtCampos[4].setText(tmpCliente.getEndereço());
- txtCampos[5].setText(tmpCliente.getCidade());
- txtCampos[6].setText(tmpCliente.getEstado());
- txtCampos[7].setText(tmpCliente.getCep());
- txtCampos[8].setText(tmpCliente.getPais());
- txtCampos[9].setText(tmpCliente.getTelefone());
- txtCampos[10].setText(tmpCliente.getEmail());
- desbloqueiaCampos(false);
- btnAtivar.setVisible(true);
- mniSalvar.setEnabled(false);
- btnSalvar.setEnabled(false);
- mniEditar.setEnabled(true);
- btnEditar.setEnabled(true);
- if(tmpCliente.getStatus() == 0){
- txtCampos[1].setForeground(Color.red);
- btnAtivar.setText("Ativar");
- }else{
- txtCampos[1].setForeground(Color.black);
- btnAtivar.setText("Desativar");
- }
- acao = 2;
- }
- public static void preencheObjeto(){
- objCliente.setCodigo(txtCampos[0].getText());
- objCliente.setNomeEmpresa(txtCampos[1].getText());
- objCliente.setNomeRepresentante(txtCampos[2].getText());
- objCliente.setCargoRepresentante(txtCampos[3].getText());
- objCliente.setEndereço(txtCampos[4].getText());
- objCliente.setCidade(txtCampos[5].getText());
- objCliente.setEstado(txtCampos[6].getText());
- objCliente.setCep(txtCampos[7].getText());
- objCliente.setPais(txtCampos[8].getText());
- objCliente.setTelefone(txtCampos[9].getText());
- objCliente.setEmail(txtCampos[10].getText());
- }
- public static void carregarLista(){
- java.util.List<ClientesVO> vetorClientes = new java.util.ArrayList<ClientesVO>();
- //Limpar lista
- //enquanto houver elementos na lista
- while(mdlClientes.getRowCount()>0){
- mdlClientes.removeRow(0);//remover o primeiro
- }
- try{
- vetorClientes = ClientesDAO.carregaClientes();
- //para cada cliente existente no vetor -> cria um objeto clienteVO
- for(ClientesVO tmpCliente: vetorClientes){
- String dados[] = new String[4];
- dados[0] = tmpCliente.getCodigo();
- dados[1] = tmpCliente.getNomeEmpresa();
- dados[2] = tmpCliente.getCidade();
- dados[3] = tmpCliente.getTelefone();
- mdlClientes.addRow(dados);
- }
- }catch(Exception erro){
- JOptionPane.showMessageDialog(null, erro.getMessage());
- }
- }
- public static boolean validaCampos(){
- //Executando varredura nos campos e verifica qual está vazio
- for(int i=0; i<txtCampos.length; i++){
- if(txtCampos[i].getText().trim().compareTo("") == 0){
- JOptionPane.showMessageDialog(null, "Preencha o campo " + strCampos[i].toUpperCase());
- txtCampos[i].grabFocus();//Movendo cursor
- return false;
- }//fechando if
- }//fechando for
- return true;//Todos os campos preenchidos
- }
- public static void alternaStatus(String tmpCodigo){
- try{
- ClientesDAO.alteraStatusCliente((tmpCodigo));
- preencheCampos(ClientesDAO.consultaCliente(1, tmpCodigo));
- }catch(Exception erro){
- JOptionPane.showMessageDialog(null, erro.getMessage());
- }
- }
- public static void limparCampos(){
- for (int i = 0; i < txtCampos.length; i++) {
- txtCampos[i].setText(null);
- }
- }
- }//fechando class
- // ===== FECHA ClientesView =====
- // ===== ClientesVO =====
- public class ClientesVO {
- //Declaração dos atributos do cliente
- public String codigo, nomeEmpresa, nomeRepresentante;
- public String cargoRepresentante, endereço, cidade, estado;
- public String cep, pais, telefone, email;
- public int status;
- //Metodo Construtor
- //Vazio - Suporte à construção de um objeto vazio p/ preenchimento dos atributos
- public ClientesVO(){
- this.setCodigo(null);
- this.setNomeEmpresa(null);
- this.setNomeRepresentante(null);
- this.setCargoRepresentante(null);
- this.setEndereço(null);
- this.setCidade(null);
- this.setEstado(null);
- this.setCep(null);
- this.setPais(null);
- this.setTelefone(null);
- this.setEmail(null);
- this.setStatus(0);
- }
- //Metodo Construtor
- //Completo - Suporte à construção de um objeto com os atributos previamente preenchidos
- 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){
- this.setCodigo(tmpCodigo);
- this.setNomeEmpresa(tmpNomeEmpresa);
- this.setNomeRepresentante(tmpNomeRepresentante);
- this.setCargoRepresentante(tmpCargoRepresentante);
- this.setEndereço(tmpEndereço);
- this.setCidade(tmpCidade);
- this.setEstado(tmpEstado);
- this.setCep(tmpCep);
- this.setPais(tmpPais);
- this.setTelefone(tmpTelefone);
- this.setEmail(tmpEmail);
- this.setStatus(tmpStatus);
- }
- //Metodo Construtor
- //Parcial - Suporte à construção de um objeto com os alguns atributos previamente preenchidos
- public ClientesVO(String tmpCodigo, String tmpNomeEmpresa){
- this.setCodigo(tmpCodigo);
- this.setNomeEmpresa(tmpNomeEmpresa);
- this.setNomeRepresentante(null);
- this.setCargoRepresentante(null);
- this.setEndereço(null);
- this.setCidade(null);
- this.setEstado(null);
- this.setCep(null);
- this.setPais(null);
- this.setTelefone(null);
- this.setEmail(null);
- this.setStatus(0);
- }
- //Métodos SET e GET
- public String getCodigo(){
- return this.codigo;
- }
- public void setCodigo(String tmpCodigo){
- this.codigo = tmpCodigo;
- }
- public String getNomeEmpresa() {
- return this.nomeEmpresa;
- }
- public void setNomeEmpresa(String tmpNomeEmpresa) {
- this.nomeEmpresa = tmpNomeEmpresa;
- }
- public String getNomeRepresentante() {
- return this.nomeRepresentante;
- }
- public void setNomeRepresentante(String tmpNomeRepresentante) {
- this.nomeRepresentante = tmpNomeRepresentante;
- }
- public String getCargoRepresentante() {
- return this.cargoRepresentante;
- }
- public void setCargoRepresentante(String tmpCargoRepresentante) {
- this.cargoRepresentante = tmpCargoRepresentante;
- }
- public String getEndereço() {
- return this.endereço;
- }
- public void setEndereço(String tmpEndereço) {
- this.endereço = tmpEndereço;
- }
- public String getCidade() {
- return this.cidade;
- }
- public void setCidade(String tmpCidade) {
- this.cidade = tmpCidade;
- }
- public String getEstado() {
- return this.estado;
- }
- public void setEstado(String tmpEstado) {
- this.estado = tmpEstado;
- }
- public String getCep() {
- return this.cep;
- }
- public void setCep(String tmpCep) {
- this.cep = tmpCep;
- }
- public String getPais() {
- return this.pais;
- }
- public void setPais(String tmpPais) {
- this.pais = tmpPais;
- }
- public String getTelefone() {
- return this.telefone;
- }
- public void setTelefone(String tmpTelefone) {
- this.telefone = tmpTelefone;
- }
- public String getEmail() {
- return this.email;
- }
- public void setEmail(String tmpEmail) {
- this.email = tmpEmail;
- }
- public int getStatus(){
- return this.status;
- }
- public void setStatus(int tmpStatus){
- this.status = tmpStatus;
- }
- }
- // ===== FECHA ClientesVO =====
- // ===== ClientesDAO =====
- import java.sql.*;
- import java.util.*;
- public class ClientesDAO {
- //classe Statement permite execução de comandos SQL
- public static Statement stClientes;
- //classe ResultSet armazena o resultado de uma instrução Select
- public static ResultSet rsClientes;
- public static void cadastraCliente(ClientesVO tmpCliente) throws Exception{
- /*******************ABERTURA DO BANCO DE DADOS*********************/
- try{
- BancoDAO.abreConexao();
- }catch(Exception erro){
- throw new Exception (erro.getMessage());
- }
- /************************INSERT*********************/
- try{
- //insert
- String sqlCadastra = "";
- sqlCadastra += "INSERT INTO CUSTOMERS(";
- sqlCadastra += "CustomerID, CompanyName,";
- sqlCadastra += "ContactName, ContactTitle,";
- sqlCadastra += "Address, City,";
- sqlCadastra += "Region, PostalCode,";
- sqlCadastra += "Country, Phone,";
- sqlCadastra += "Fax, Status) values (";
- sqlCadastra += "'" + tmpCliente.getCodigo() + "',";
- sqlCadastra += "'" + tmpCliente.getNomeEmpresa() + "',";
- sqlCadastra += "'" + tmpCliente.getNomeRepresentante() + "',";
- sqlCadastra += "'" + tmpCliente.getCargoRepresentante()+ "',";
- sqlCadastra += "'" + tmpCliente.getEndereço()+ "',";
- sqlCadastra += "'" + tmpCliente.getCidade()+ "',";
- sqlCadastra += "'" + tmpCliente.getEstado()+ "',";
- sqlCadastra += "'" + tmpCliente.getCep()+ "',";
- sqlCadastra += "'" + tmpCliente.getPais()+ "',";
- sqlCadastra += "'" + tmpCliente.getTelefone()+ "',";
- sqlCadastra += "'" + tmpCliente.getEmail()+ "',1)";
- stClientes = BancoDAO.connSistema.createStatement();
- //utilizado para INSERT, DELETE e UPDATE
- stClientes.executeUpdate(sqlCadastra);
- }catch(Exception erro){
- throw new Exception ("FALHA NA INSERÇÃO, VERIFIQUE A SINTAXE DO INSERT.\nErro Original: " + erro.getMessage());
- }
- /************************ENCERRAMENTO DO BANCO DE DADOS*********************/
- try{
- BancoDAO.fechaConexao();
- }catch(Exception erro){
- throw new Exception (erro.getMessage());
- }
- }//fechando cadastraCliente
- public static ClientesVO consultaCliente(int tmpTipo, String tmpBusca) throws Exception{
- //Objeto com os dados do cliente que será retornado
- ClientesVO tmpCliente = new ClientesVO();
- /*******************ABERTURA DO BANCO DE DADOS*********************/
- try{
- BancoDAO.abreConexao();
- }catch(Exception erro){
- throw new Exception (erro.getMessage());
- }
- /************************EXECUÇÃO SQL*********************/
- try{
- String sqlConsulta = "";
- if (tmpTipo == 1){
- //por Código
- sqlConsulta = "SELECT * FROM CUSTOMERS WHERE CustomerID like '" + tmpBusca + "'";
- }else if(tmpTipo == 2){
- //por Nome
- sqlConsulta = "SELECT * FROM CUSTOMERS WHERE CompanyName like '" + tmpBusca + "'";
- }
- //executando instrução SELECT e armazenando
- stClientes = BancoDAO.connSistema.createStatement();//ativando statement para o banco selecionado
- rsClientes = stClientes.executeQuery(sqlConsulta);
- if(rsClientes.next()){//se houver clientes
- tmpCliente.setCodigo(rsClientes.getString("CustomerID"));
- tmpCliente.setNomeEmpresa(rsClientes.getString("CompanyName"));
- tmpCliente.setNomeRepresentante(rsClientes.getString("ContactName"));
- tmpCliente.setCargoRepresentante(rsClientes.getString("ContactTitle"));
- tmpCliente.setEndereço(rsClientes.getString("Address"));
- tmpCliente.setCidade(rsClientes.getString("City"));
- tmpCliente.setEstado(rsClientes.getString("Region"));
- tmpCliente.setCep(rsClientes.getString("PostalCode"));
- tmpCliente.setPais(rsClientes.getString("Country"));
- tmpCliente.setTelefone(rsClientes.getString("Phone"));
- tmpCliente.setEmail(rsClientes.getString("Fax"));
- tmpCliente.setStatus(rsClientes.getInt("Status"));
- }
- //SELECT
- }catch(Exception erro){
- throw new Exception ("FALHA NO SELECT, VERIFIQUE A SINTÁXE DO COMANDO E O NOME DOS CAMPOS/TABELA\nErro Original" + erro.getMessage());
- }
- /************************ENCERRAMENTO DO BANCO DE DADOS*********************/
- try{
- BancoDAO.fechaConexao();
- }catch(Exception erro){
- }
- return tmpCliente;
- }
- public static void excluiCliente(String tmpCodigo) throws Exception{
- }
- public static void alteraCliente(ClientesVO tmpCliente, String tmpCodigo) throws Exception{
- /*******************ABERTURA DO BANCO DE DADOS*********************/
- try{
- BancoDAO.abreConexao();
- }catch(Exception erro){
- throw new Exception (erro.getMessage());
- }
- /*********************UPDATE****************************/
- try{
- String sqlAltera = "";
- sqlAltera += "UPDATE CUSTOMERS set ";
- sqlAltera += "companyName = '" + tmpCliente.getNomeEmpresa() + "',";
- sqlAltera += "contactName = '" + tmpCliente.getNomeRepresentante()+ "',";
- sqlAltera += "contactTitle = '" + tmpCliente.getCargoRepresentante()+ "',";
- sqlAltera += "address = '" + tmpCliente.getEndereço()+ "',";
- sqlAltera += "city = '" + tmpCliente.getCidade()+ "',";
- sqlAltera += "region = '" + tmpCliente.getEstado()+ "',";
- sqlAltera += "country = '" + tmpCliente.getPais()+ "',";
- sqlAltera += "postalCode = '" + tmpCliente.getCep()+ "',";
- sqlAltera += "phone = '" + tmpCliente.getTelefone()+ "',";
- sqlAltera += "fax = '" + tmpCliente.getEmail()+ "' where ";
- sqlAltera += "customerID like '" + tmpCodigo + "'";
- stClientes = BancoDAO.connSistema.createStatement();
- stClientes.executeUpdate(sqlAltera);
- }catch(Exception erro){
- throw new Exception ("Falha no Update. Verifique a sintaxe." + "\nErro Original: " + erro.getMessage());
- }
- /******************ENCERRAMENTO DO BANCO DE DADOS*********************/
- try{
- BancoDAO.fechaConexao();
- }catch(Exception erro){
- throw new Exception (erro.getMessage());
- }
- }
- public static void alteraStatusCliente(String tmpCodigo) throws Exception{
- ClientesVO tmpCliente = new ClientesVO();
- /*******************ABERTURA DO BANCO DE DADOS*********************/
- try{
- BancoDAO.abreConexao();
- }catch(Exception erro){
- throw new Exception (erro.getMessage());
- }
- /************************EXECUÇÃO SQL*********************/
- try{
- tmpCliente = consultaCliente(1, tmpCodigo);
- BancoDAO.abreConexao();
- int novoStatus;
- if(tmpCliente.getStatus() == 0){
- novoStatus = 1;
- }else{
- novoStatus = 0;
- }
- //update status
- String sqlStatus = "Update customers set status = " + novoStatus + " where customerid like '" + tmpCodigo + "'";
- stClientes = BancoDAO.connSistema.createStatement();
- stClientes.executeUpdate(sqlStatus);
- }catch(Exception erro){
- throw new Exception ("FALHA NA ALTERAÇÃO, VERIFIQUE INSTRUÇÃO UPDATE\nErro Original" + erro.getMessage());
- }
- /************************ENCERRAMENTO DO BANCO DE DADOS*********************/
- try{
- BancoDAO.fechaConexao();
- }catch(Exception erro){
- }
- }
- public static List<ClientesVO> carregaClientes() throws Exception{
- //declarando e instanciando vetor de ClientesVO
- List<ClientesVO> vetorClientes = new ArrayList<ClientesVO>();
- try{
- BancoDAO.abreConexao();
- }catch(Exception erro){
- throw new Exception(erro.getMessage());
- }
- //EXECUÇÃO DO SELECT
- try{
- String sqlClientes = "Select * from CUSTOMERS";
- stClientes = BancoDAO.connSistema.createStatement();
- rsClientes = stClientes.executeQuery(sqlClientes);
- //enquanto houver clientes na tabela
- while(rsClientes.next()){
- ClientesVO clienteAtual = new ClientesVO();
- clienteAtual.setCodigo(rsClientes.getString("CustomerID"));
- clienteAtual.setNomeEmpresa(rsClientes.getString("CompanyName"));
- clienteAtual.setCidade(rsClientes.getString("City"));
- clienteAtual.setTelefone(rsClientes.getString("Phone"));
- //add clienteAtual ao vetor
- vetorClientes.add(clienteAtual);
- }
- }catch(Exception erro){
- throw new Exception("Falha no carregamento da lista.\nErro original: " + erro.getMessage());
- }
- try{
- BancoDAO.fechaConexao();
- }catch(Exception erro){
- throw new Exception(erro.getMessage());
- }
- return vetorClientes;
- }//fechando carregaClientes
- }
- // ===== FECHA ClientesDAO =====
- // ===== SistemaControl =====
- //Projeto NorthwindSystem
- public class SistemaControl {
- public static void main(String[] args) {
- TelaView ObjTela = new TelaView();
- }
- }
- // ===== FECHA SistemaControl =====
- // ===== SistemaView =====
- import javax.swing.*;
- import java.awt.*;
- import java.awt.event.*;
- public class SistemaView extends JFrame implements ActionListener {
- //Declaração dos objetos
- public static Container ctnPrincipal, ctnTopo, ctnMenu;
- public static JLabel lblBanner;
- public static JButton btnMenu[];
- public static String modulos[] = {"CLIENTES", "FUNCIONÁRIOS", "FORNECEDOR", "PRODUTOS",
- "VENDAS", "CAIXA", "USUÁRIOS", "SAIR"};
- public static JDesktopPane dskJanelas;
- public SistemaView(){
- super("Northwind System - Sistema Gerenciador de Vendas");
- //Construção dos objetos
- ctnPrincipal = new Container();
- ctnPrincipal.setLayout(new BorderLayout());
- ctnTopo = new Container();
- ctnTopo.setLayout(new GridLayout(2,1));
- ctnMenu = new Container();
- ctnMenu.setLayout(new GridLayout(2,4));
- lblBanner = new JLabel(new ImageIcon("img/banner.jpg"));
- btnMenu = new JButton[8];
- for(int i=0; i<btnMenu.length; i++){
- btnMenu[i] = new JButton(new ImageIcon("img/" + i + ".jpg"));
- btnMenu[i].addActionListener(this);
- btnMenu[i].setToolTipText(modulos[i]);//'dica' do botão
- ctnMenu.add(btnMenu[i]);
- }
- //Objeto que permite abertura de janelas internas
- dskJanelas = new JDesktopPane();
- //Adicionando objetos na janela
- this.add(ctnPrincipal); //add principal na janela
- ctnPrincipal.add(ctnTopo, BorderLayout.NORTH);//add topo no norte do principal
- ctnTopo.add(lblBanner);//add banner na primeira célula do topo
- ctnTopo.add(ctnMenu);//add banner na segunda linha do topo
- ctnPrincipal.add(dskJanelas, BorderLayout.CENTER);//add desktop no centro do principal
- //chamando fechar janela ao clica no X do JFrame
- this.addWindowListener(new WindowAdapter() {
- public void windowClosing(WindowEvent evt){
- if(!fecharJanela()){
- setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
- }else{
- System.exit(0);
- }
- }
- }
- );
- this.setSize(montarTela());
- this.show();
- //Encerra o processo ao fechar a janela
- this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
- }//fechando Construtor
- public static Dimension montarTela(){
- Toolkit info = Toolkit.getDefaultToolkit();
- Dimension res = info.getScreenSize();
- return res;
- }
- public void actionPerformed(ActionEvent evt){
- if(evt.getSource() == btnMenu[0]){
- dskJanelas.add(new ClientesView(modulos[0]));
- btnMenu[0].setEnabled(false);
- }
- if (evt.getSource() == btnMenu[7]){
- if(fecharJanela())
- System.exit(0);
- }
- }//Fechando ActionPerformed
- public static boolean fecharJanela(){
- int resp = JOptionPane.showConfirmDialog(null, "Deseja encerrar o sistema?", "SAIR", JOptionPane.YES_NO_OPTION);
- if(resp == JOptionPane.YES_OPTION)
- return true;
- else
- return false;
- }
- }
- // ===== FECHA SistemaView =====
- // ===== TelaView =====
- import java.awt.*;
- import javax.swing.*;
- public class TelaView extends JFrame {
- //Variaveis de coordenadas da abertura da janela
- public static int xFinal, yFinal;
- public TelaView(){
- int largTela = 640, altTela = 480;
- Container ctnTela = new Container();
- ctnTela.setLayout(null);
- JLabel lblFundo = new JLabel(new ImageIcon("img/imgFundo.png"));
- this.add(ctnTela);
- lblFundo.setBounds(0, 0, largTela, altTela);
- ctnTela.add(lblFundo);
- centralizar(largTela, altTela);
- this.setLocation(xFinal, yFinal);
- this.setUndecorated(true);//Tira as bordas da janela
- this.setSize(largTela,altTela);
- try{
- this.show();//exibindo
- Thread.sleep(1000);//aguardando
- this.dispose();//encerrando
- //abrindo telaPrincipal
- SistemaView objTelaSistema = new SistemaView();
- }catch(Exception erro){
- }
- }//Fim construtor
- public static void centralizar(int tmpLarg, int tmpAlt){
- Toolkit info = Toolkit.getDefaultToolkit();
- Dimension dim = info.getScreenSize();
- xFinal = (int) (dim.getWidth()/2) - (tmpLarg/2);
- yFinal = (int) (dim.getHeight()/2) - (tmpAlt/2);
- }
- }
- // ===== FECHA TelaView =====
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement