JOSIEL S. MOURA MANIPULAÇÃO DE BANCO DE DADOS UTILIZANDO INTERFACE GRÁFICA ORIENTADO A PROJETO: CONTROLE DE ESTOQUE 2012
JOSIEL S. MOURA MANIPULAÇÃO DE BANCO DE DADOS UTILIZANDO INTERFACE GRÁFICA ORIENTADO A PROJETO: CONTROLE DE ESTOQUE 2012
Sumário INTRODUÇÃO... 3 PADRÃO DAO... 4 ESTUDO DE CASO... 6 Banco de Dados... 6 Entidade... 7 Fornecedor... 7 Produto... 8 Movimento... 9 Dao... 11 Conexão... 11 Fornecedor... 12 Produto... 13 Movimento... 15 Formulários... 17 Principal... 17 Fornecedor... 18 Produto... 24 Entrada... 30 Busca de produtos... 32 Saída... 35
REFENRÊNCIAS BIBLIOGRÁFICAS... 38
INTRODUÇÃO A ideia de padrões foi apresentada por Christopher Alexander em 1977 no contexto de Arquitetura (de prédios e cidades). Cada padrão descreve um problema que ocorre repetidamente, de novo e de novo, em nosso ambiente, e então descreve a parte central da solução para aquele problema de uma forma que você pode usar esta solução um milhão de vezes, sem nunca implementá-la duas vezes da mesma forma. Um padrão de projeto é uma espécie de gabarito para como resolver um problema, ou melhor dizendo, é uma solução elegante na resolução de problemas. 3
PADRÃO DAO A maioria das aplicações empresariais usa normalmente sistemas de gerenciamento de bancos de dados relacional (RDBMS, relational database management system) como armazenamento persistente. Entretanto, estamos trabalhando em Java, que é Orientado a Objeto. Misturar a lógica de persistência com a lógica de aplicação cria uma dependência direta entre a implementação da aplicação e do armazenamento persistente. Tal dependência de código nos componentes torna difícil e maçante migrar a aplicação de um tipo de fonte de dados para outro. Quando as fontes de dados são alteradas, os componentes devem ser modificados para tratar o novo tipo de fonte de dados. Use um Data Access Object (DAO) para abstrair e encapsular todo acesso ao armazenamento persistente. O DAO gerencia a conexão com a fonte de dados para obter e armazenar dados. O DAO funciona como um tradutor dos mundos. O DAO deve saber buscar os dados do banco relacional e converter em objetos para ser usado pela aplicação. Semelhantemente, deve saber como pegar os objetos, converter em instruções SQL e 4
mandar para o banco de dados relacional. É assim que um DAO trabalha. O principal objetivo de um DAO é encapsular o acesso e a manipulação de dados em uma camada separada. 5
ESTUDO DE CASO Banco de Dados Abaixo temos o diagrama de Entidade-Relacionamento para o sistema de controle de estoque que terá foco no cadastro de produtos e na movimentação (entrada e saída) desses produtos. Figura 1: Diagrama de entidade e relacionamento 6
Entidade A entidade é a representação da tabela do banco de dados em nosso aplicativo. Deve ser criados os métodos get s e set s para implementar o encapsulamento de nosso código. Fornecedor 1 public class Fornecedor { 2 private int id; 3 private String nome; 4 private String telefone; 5 private String cnpj; 6 7 public int getid() { 8 return id; 9 } 10 11 public void setid(int id) { 12 this.id = id; 13 } 14 15 public String getnome() { 16 return nome; 17 } 18 19 public void setnome(string nome) { 20 this.nome = nome; 21 } 22 23 public String gettelefone() { 24 return telefone; 25 } 26 27 public void settelefone(string telefone) { 28 this.telefone = telefone; 29 } 30 31 public String getcnpj() { 7
32 return cnpj; 33 } 34 35 public void setcnpj(string cnpj) { 36 this.cnpj = cnpj; 37 } 38 39 } Listagem 1: Classe Fornecedor.java Produto 1 public class Produto { 2 private int id; 3 private String codigo; 4 private String nome; 5 private double estoque; 6 private double valor; 7 private Fornecedor fornecedor; 8 9 public int getid() { 10 return id; 11 } 12 13 public void setid(int id) { 14 this.id = id; 15 } 16 17 public String getcodigo() { 18 return codigo; 19 } 20 21 public void setcodigo(string codigo) { 22 this.codigo = codigo; 23 } 24 25 public String getnome() { 26 return nome; 8
27 } 28 29 public void setnome(string nome) { 30 this.nome = nome; 31 } 32 33 public double getestoque() { 34 return estoque; 35 } 36 37 public void setestoque(double estoque) { 38 this.estoque = estoque; 39 } 40 41 public double getvalor() { 42 return valor; 43 } 44 45 public void setvalor(double valor) { 46 this.valor = valor; 47 } 48 49 public Fornecedor getfornecedor() { 50 return fornecedor; 51 } 52 53 public void setfornecedor(fornecedor fornecedor) { 54 this.fornecedor = fornecedor; 55 } 56 57 } Movimento 1 public class Movimento { 2 private int id; 3 private String tipo; 9
4 private double quantidade; 5 private String data; 6 private Produto produto; 7 8 public int getid() { 9 return id; 10 } 11 12 public void setid(int id) { 13 this.id = id; 14 } 15 16 public String gettipo() { 17 return tipo; 18 } 19 20 public void settipo(string tipo) { 21 this.tipo = tipo; 22 } 23 24 public double getquantidade() { 25 return quantidade; 26 } 27 28 public void setquantidade(double quantidade) { 29 this.quantidade = quantidade; 30 } 31 32 public String getdata() { 33 return data; 34 } 35 36 public void setdata(string data) { 37 this.data = data; 38 } 39 40 public Produto getproduto() { 41 return produto; 42 } 43 10
44 public void setproduto(produto produto) { 45 this.produto = produto; 46 } 47 48 } Dao Primeiramente precisamos de uma classe que estabeleça a conexão com o banco de dados: Conexão 1 import java.sql.*; 2 public class Conexao { 3 private String driver="com.mysql.jdbc.driver"; 4 private String url="jdbc:mysql://localhost:3306/db_aluno"; 5 private String usuario = "root"; 6 private String senha = ""; 7 8 public Statement stm; 9 public ResultSet rs; 10 11 public void conectar() throws Exception{ 12 Class.forName(driver); 13 Connection con = DriverManager.getConnection(url,usuario,senha); 14 stm = con.createstatement(); 15 } 16 } Listagem 2: Classe Conexao.java 11
Vamos criar uma classe AlunoDAO que possui os métodos para manipular (salvar, atualizar, apagar e consultar) um objeto Aluno. Fornecedor 1 import java.util.linkedlist; 2 import java.util.list; 3 4 public class FornecedorDao extends Conexao{ 5 Fornecedor f = new Fornecedor(); 6 String sql; 7 8 public FornecedorDao() throws Exception{ 9 conectar(); 10 } 11 12 public Fornecedor getfornecedor(int id)throws Exception{ 13 sql="select * FROM fornecedor WHERE idfornecedor="+id; 14 rs = stm.executequery(sql); 15 if(rs.next()){ 16 f.setid( rs.getint(1)); 17 f.setnome(rs.getstring(2)); 18 f.settelefone(rs.getstring(3)); 19 f.setcnpj(rs.getstring(4)); 20 } 21 return f; 22 } 23 24 public List<Fornecedor> pesquisar(string nome)throws Exception{ 25 List<Fornecedor> fornecedores = new LinkedList(); 26 sql="select * FROM fornecedor WHERE nome_fornecedor LIKE '"+nome+"%'"; 27 rs = stm.executequery(sql); 28 while(rs.next()){ 29 f = new Fornecedor(); 30 f.setid( rs.getint(1)); 12
31 f.setnome(rs.getstring(2)); 32 f.settelefone(rs.getstring(3)); 33 f.setcnpj(rs.getstring(4)); 34 fornecedores.add(f); 35 } 36 return fornecedores; 37 } 38 39 public void cadastrar(fornecedor f)throws Exception{ 40 sql="insert INTO fornecedor(nome_fornecedor,telefone,cnpj)" 41 +" values('"+f.getnome()+"','"+f.gettelefone()+"','"+f.getcnpj()+"')"; 42 stm.executeupdate(sql); 43 } 44 45 public void alterar(fornecedor f)throws Exception{ 46 sql="update fornecedor SET nome_fornecedor='"+f.getnome()+"'," 47 + " telefone='"+f.gettelefone()+"', cnpj='"+f.getcnpj()+"'" 48 + " WHERE idfornecedor="+f.getid(); 49 stm.executeupdate(sql); 50 } 51 52 public void excluir(int id)throws Exception{ 53 sql="delete FROM fornecedor WHERE idfornecedor="+id; 54 stm.executeupdate(sql); 55 } 56 } Listagem 3: Classe FornecedorDao.java Produto 1 import java.util.linkedlist; 2 import java.util.list; 3 4 public class ProdutoDao extends Conexao{ 5 Produto p = new Produto(); 13
6 FornecedorDao fornecedordao = new FornecedorDao(); 7 String sql; 8 9 public ProdutoDao() throws Exception { 10 conectar(); 11 } 12 13 public Produto getproduto(int id)throws Exception{ 14 sql="select * FROM produto WHERE idproduto="+id; 15 rs = stm.executequery(sql); 16 if(rs.next()){ 17 p = new Produto(); 18 p.setid( rs.getint(1)); 19 p.setcodigo( rs.getstring(2)); 20 p.setnome(rs.getstring(3)); 21 p.setestoque(rs.getdouble(4)); 22 p.setvalor(rs.getdouble(5)); 23 p.setfornecedor(fornecedordao.getfornecedor(rs.getint(6))); 24 } 25 return p; 26 } 27 28 public List<Produto> pesquisar(string nome)throws Exception{ 29 List<Produto> produtos = new LinkedList(); 30 sql="select * FROM produto WHERE nome_produto LIKE '"+nome+"%' ORDER BY nome_produto"; 31 rs = stm.executequery(sql); 32 while(rs.next()){ 33 p = new Produto(); 34 p.setid( rs.getint(1)); 35 p.setcodigo( rs.getstring(2)); 36 p.setnome(rs.getstring(3)); 37 p.setestoque(rs.getdouble(4)); 38 p.setvalor(rs.getdouble(5)); 39 p.setfornecedor(fornecedordao.getfornecedor(rs.getint(6))); 40 produtos.add(p); 41 } 42 return produtos; 43 } 44 14
45 public void cadastrar(produto p)throws Exception{ 46 sql="insert INTO produto(codigo,nome_produto,estoque,valor,fornecedor_idfornecedor)" 47 +" values('"+p.getcodigo()+"','"+p.getnome()+"', 0,"+p.getValor()+","+p.getFornecedor().getId()+")"; 48 stm.executeupdate(sql); 49 } 50 51 public void alterar(produto p)throws Exception{ 52 sql="update produto SET codigo='"+p.getcodigo()+"', nome_produto='"+p.getnome()+"'," 53 + " valor="+p.getvalor()+", fornecedor_idfornecedor="+p.getfornecedor().getid() 54 + " WHERE idproduto="+p.getid(); 55 stm.executeupdate(sql); 56 } 57 58 public void excluir(int id)throws Exception{ 59 sql="delete FROM produto WHERE idproduto="+id; 60 stm.executeupdate(sql); 61 } 62 } Movimento 1 2 public class MovimentoDao extends Conexao { 3 4 String sql; 5 6 public MovimentoDao() throws Exception { 7 conectar(); 8 } 9 10 public boolean registarmovimento(movimento m) throws Exception { 11 if (atualizarestoque(m)) { 12 sql = "INSERT INTO 15
movimento(tipo,quantidade,data,produto_idproduto)" 13 + "VALUES('" + m.gettipo() + "'," + m.getquantidade() + ",'" + m.getdata() 14 + "'," + m.getproduto().getid() + ")"; 15 stm.executeupdate(sql); 16 return true; 17 } 18 return false; 19 } 20 21 private boolean atualizarestoque(movimento m) throws Exception { 22 ProdutoDao produtodao = new ProdutoDao(); 23 double estoque = produtodao.getproduto(m.getproduto().getid()).getestoque(); 24 if (m.gettipo().equals("entrada")) { 25 estoque += m.getquantidade(); 26 } else { 27 if (estoque > m.getquantidade()) { 28 estoque -= m.getquantidade(); 29 } else { 30 return false; 31 } 32 } 33 sql = "UPDATE produto SET estoque=" + estoque + " WHERE idproduto=" + m.getproduto().getid(); 34 stm.executeupdate(sql); 35 return true; 36 } 37 } 16
Formulários Principal Abaixo temos os eventos para os botões 120 private void jbfornecedoractionperformed(java.awt.event.actionevent 121 try { 122 new FormularioFornecedor().show(); 123 } catch (Exception ex) { 124 JOptionPane.showMessageDialog(null, ex); 125 } 17
126 } 127 128 private void jbprodutoactionperformed(java.awt.event.actionevent 129 try { 130 new FormularioProduto().show(); 131 } catch (Exception ex) { 132 JOptionPane.showMessageDialog(null, ex); 133 } 134 } 135 136 private void jbentradaactionperformed(java.awt.event.actionevent 137 try { 138 new FormularioEntrada().show(); 139 } catch (Exception ex) { 140 JOptionPane.showMessageDialog(null, ex); 141 } 142 } 143 144 private void jbsaidaactionperformed(java.awt.event.actionevent 145 try { 146 new FormularioSaida().show(); 147 } catch (Exception ex) { 148 JOptionPane.showMessageDialog(null, ex); 149 } 150 } Figura 2: Formulário principal Fornecedor 18
1 2 import java.util.linkedlist; 3 import java.util.list; 4 import java.util.logging.level; 5 import java.util.logging.logger; 6 import javax.swing.joptionpane; 7 8 /* 9 * To change this template, choose Tools Templates 19
10 * and open the template in the editor. 11 */ 12 /** 13 * 14 * @author Josiel 15 */ 16 public class FormularioFornecedor extends javax.swing.jframe { 17 18 private Fornecedor fornecedor = new Fornecedor(); 19 private List<Fornecedor> fornecedores = new LinkedList<>(); 20 private FornecedorDao fornecedordao = new FornecedorDao(); 21 int posicao; 22 23 /** 24 * Creates new form FormularioFornecedor 25 */ 26 public FormularioFornecedor() throws Exception{ 27 initcomponents(); 28 } 29 30 private void limparcampos() { 31 tfid.settext(null); 32 tfnome.settext(null); 33 tftelefone.settext(null); 34 tfcnpj.settext(null); 35 } 36 37 private void getfornecedor() { 38 if (!tfid.gettext().equals("")) { 39 fornecedor.setid(integer.parseint(tfid.gettext())); 40 } 41 fornecedor.setnome(tfnome.gettext()); 42 fornecedor.settelefone(tftelefone.gettext()); 43 fornecedor.setcnpj(tfcnpj.gettext()); 44 } 45 46 private void setfornecedor(fornecedor f) { 47 tfid.settext(string.valueof(f.getid())); 48 tfnome.settext(f.getnome()); 49 tftelefone.settext(f.gettelefone()); 20
50 tfcnpj.settext(f.getcnpj()); 51 } 52 53 //Código omitido 249 250 private void btcadastraractionperformed(java.awt.event.actionevent 251 try { 252 getfornecedor(); 253 fornecedordao.cadastrar(fornecedor); 254 JOptionPane.showMessageDialog(null, "Cadastrado com sucesso!"); 255 limparcampos(); 256 } catch (Exception ex) { 257 JOptionPane.showMessageDialog(null, ex); 258 } 259 } 260 261 private void btfecharactionperformed(java.awt.event.actionevent 262 dispose(); 263 } 264 265 private void btpesquisaractionperformed(java.awt.event.actionevent 266 try { 267 fornecedores = fornecedordao.pesquisar(tfnome.gettext()); 268 posicao = 0; 269 setfornecedor(fornecedores.get(posicao)); 270 } catch (Exception ex) { 271 JOptionPane.showMessageDialog(null, ex); 272 } 273 } 274 275 private void btproximoactionperformed(java.awt.event.actionevent 276 if (posicao < fornecedores.size() - 1) { 277 posicao++; 278 setfornecedor(fornecedores.get(posicao)); 279 } 21
280 } 281 282 private void btanterioractionperformed(java.awt.event.actionevent 283 if (posicao > 0) { 284 posicao--; 285 setfornecedor(fornecedores.get(posicao)); 286 } 287 } 288 289 private void btprimeiroactionperformed(java.awt.event.actionevent 290 posicao = 0; 291 setfornecedor(fornecedores.get(posicao)); 292 } 293 294 private void btultimoactionperformed(java.awt.event.actionevent 295 posicao = fornecedores.size() - 1; 296 setfornecedor(fornecedores.get(posicao)); 297 } 298 299 private void btalteraractionperformed(java.awt.event.actionevent 300 try { 301 getfornecedor(); 302 fornecedordao.alterar(fornecedor); 303 JOptionPane.showMessageDialog(null, "Alterado com sucesso!"); 304 limparcampos(); 305 } catch (Exception ex) { 306 JOptionPane.showMessageDialog(null, ex); 307 } 308 } 309 310 private void btexcluiractionperformed(java.awt.event.actionevent 311 try { 312 getfornecedor(); 313 fornecedordao.excluir(fornecedor.getid()); 314 JOptionPane.showMessageDialog(null, "Excluido com 22
sucesso!"); 315 limparcampos(); 316 } catch (Exception ex) { 317 JOptionPane.showMessageDialog(null, ex); 318 } 319 } 320 321 private void btnovoactionperformed(java.awt.event.actionevent 322 limparcampos(); 323 } 324 325 //Código omitido 351 352 /* Create and display the form */ 353 java.awt.eventqueue.invokelater(new Runnable() { 354 public void run() { 355 try { 356 new FormularioFornecedor().setVisible(true); 357 } catch (Exception ex) { 358 JOptionPane.showMessageDialog(null, ex); 359 } 360 } 361 }); 362 } 363 // Variables declaration - do not modify 364 private javax.swing.jbutton btalterar; 365 private javax.swing.jbutton btanterior; 366 private javax.swing.jbutton btcadastrar; 367 private javax.swing.jbutton btexcluir; 368 private javax.swing.jbutton btfechar; 369 private javax.swing.jbutton btnovo; 370 private javax.swing.jbutton btpesquisar; 371 private javax.swing.jbutton btprimeiro; 372 private javax.swing.jbutton btproximo; 373 private javax.swing.jbutton btultimo; 374 private javax.swing.jbutton jbutton10; 375 private javax.swing.jlabel jlabel1; 376 private javax.swing.jlabel jlabel2; 377 private javax.swing.jlabel jlabel3; 23
378 private javax.swing.jlabel jlabel4; 379 private javax.swing.jtextfield tfcnpj; 380 private javax.swing.jtextfield tfid; 381 private javax.swing.jtextfield tfnome; 382 private javax.swing.jtextfield tftelefone; 383 // End of variables declaration 384 } Produto 2 import java.util.linkedlist; 3 import java.util.list; 4 import java.util.logging.level; 5 import java.util.logging.logger; 6 import javax.swing.joptionpane; 7 8 /* 24
9 * To change this template, choose Tools Templates 10 * and open the template in the editor. 11 */ 12 /** 13 * 14 * @author Josiel 15 */ 16 public class FormularioProduto extends javax.swing.jframe { 17 18 private Produto produto = new Produto(); 19 private List<Produto> produtos = new LinkedList<>(); 20 private ProdutoDao produtodao = new ProdutoDao(); 21 private List<Fornecedor> fornecedores = new LinkedList<>(); 22 private FornecedorDao fornecedordao = new FornecedorDao(); 23 int posicao; 24 25 /** 26 * Creates new form FormularioFornecedor 27 */ 28 public FormularioProduto() throws Exception{ 29 initcomponents(); 30 listarfornecedores(); 31 } 32 33 private void listarfornecedores() throws Exception { 34 fornecedores = fornecedordao.pesquisar(""); 35 cbfornecedor.additem("selecione um Fornecedor"); 36 for (int i = 0; i < fornecedores.size(); i++) { 37 cbfornecedor.additem(fornecedores.get(i).getnome()); 38 } 39 } 40 41 private void limparcampos() { 42 tfid.settext(null); 43 tfcodigo.settext(null); 44 tfnome.settext(null); 45 tfvalor.settext(null); 46 cbfornecedor.setselectedindex(0); 47 } 48 25
49 private void getfornecedor() throws Exception{ 50 if (!tfid.gettext().equals("")) { 51 produto.setid(integer.parseint(tfid.gettext())); 52 } 53 produto.setcodigo(tfcodigo.gettext()); 54 produto.setnome(tfnome.gettext()); 55 produto.setvalor(double.parsedouble(tfvalor.gettext())); 56 produto.setfornecedor( fornecedordao.pesquisar( cbfornecedor.getselecteditem().tostring()).get(0)); 57 } 58 59 private void setfornecedor(produto p) { 60 tfid.settext(string.valueof(p.getid())); 61 tfcodigo.settext(p.getcodigo()); 62 tfnome.settext(p.getnome()); 63 tfvalor.settext(string.valueof(p.getvalor())); 64 cbfornecedor.setselecteditem(p.getfornecedor().getnome()); 65 } 66 67 //Código omitido 280 281 private void btcadastraractionperformed(java.awt.event.actionevent 282 try { 283 getfornecedor(); 284 produtodao.cadastrar(produto); 285 JOptionPane.showMessageDialog(null, "Cadastrado com sucesso!"); 286 limparcampos(); 287 } catch (Exception ex) { 288 JOptionPane.showMessageDialog(null, ex); 289 } 290 } 291 292 private void btfecharactionperformed(java.awt.event.actionevent 293 dispose(); 294 } 295 296 private void 26
btpesquisaractionperformed(java.awt.event.actionevent 297 try { 298 produtos = produtodao.pesquisar(tfnome.gettext()); 299 posicao = 0; 300 setfornecedor(produtos.get(posicao)); 301 } catch (Exception ex) { 302 JOptionPane.showMessageDialog(null, ex); 303 } 304 } 305 306 private void btproximoactionperformed(java.awt.event.actionevent 307 if (posicao < produtos.size() - 1) { 308 posicao++; 309 setfornecedor(produtos.get(posicao)); 310 } 311 } 312 313 private void btanterioractionperformed(java.awt.event.actionevent 314 if (posicao > 0) { 315 posicao--; 316 setfornecedor(produtos.get(posicao)); 317 } 318 } 319 320 private void btprimeiroactionperformed(java.awt.event.actionevent 321 posicao = 0; 322 setfornecedor(produtos.get(posicao)); 323 } 324 325 private void btultimoactionperformed(java.awt.event.actionevent 326 posicao = produtos.size() - 1; 327 setfornecedor(produtos.get(posicao)); 328 } 329 330 private void btalteraractionperformed(java.awt.event.actionevent 27
331 try { 332 getfornecedor(); 333 produtodao.alterar(produto); 334 JOptionPane.showMessageDialog(null, "Alterado com sucesso!"); 335 limparcampos(); 336 } catch (Exception ex) { 337 JOptionPane.showMessageDialog(null, ex); 338 } 339 } 340 341 private void btexcluiractionperformed(java.awt.event.actionevent 342 try { 343 getfornecedor(); 344 produtodao.excluir(produto.getid()); 345 JOptionPane.showMessageDialog(null, "Excluido com sucesso!"); 346 limparcampos(); 347 } catch (Exception ex) { 348 JOptionPane.showMessageDialog(null, ex); 349 } 350 } 351 352 private void btnovoactionperformed(java.awt.event.actionevent 353 limparcampos(); 354 } 355 356 //Código omitido 382 383 /* Create and display the form */ 384 java.awt.eventqueue.invokelater(new Runnable() { 385 public void run() { 386 try { 387 new FormularioFornecedor().setVisible(true); 388 } catch (Exception ex) { 389 JOptionPane.showMessageDialog(null, ex); 390 } 391 } 392 }); 28
393 } 394 // Variables declaration - do not modify 395 private javax.swing.jbutton btalterar; 396 private javax.swing.jbutton btanterior; 397 private javax.swing.jbutton btcadastrar; 398 private javax.swing.jbutton btexcluir; 399 private javax.swing.jbutton btfechar; 400 private javax.swing.jbutton btnovo; 401 private javax.swing.jbutton btpesquisar; 402 private javax.swing.jbutton btprimeiro; 403 private javax.swing.jbutton btproximo; 404 private javax.swing.jbutton btultimo; 405 private javax.swing.jcombobox cbfornecedor; 406 private javax.swing.jbutton jbutton10; 407 private javax.swing.jlabel jlabel1; 408 private javax.swing.jlabel jlabel2; 409 private javax.swing.jlabel jlabel3; 410 private javax.swing.jlabel jlabel4; 411 private javax.swing.jlabel jlabel5; 412 private javax.swing.jtextfield tfcodigo; 413 private javax.swing.jtextfield tfid; 414 private javax.swing.jtextfield tfnome; 415 private javax.swing.jtextfield tfvalor; 416 // End of variables declaration 417 } 29
Entrada 2 import java.util.logging.level; 3 import java.util.logging.logger; 4 import javax.swing.joptionpane; 5 6 /* 7 * To change this template, choose Tools Templates 8 * and open the template in the editor. 9 */ 10 11 /** 12 * 13 * @author Josiel 14 */ 15 public class FormularioEntrada extends javax.swing.jframe { 16 17 /** 18 * Creates new form FormularioEntrada 19 */ 20 public FormularioEntrada() { 21 initcomponents(); 22 } 24 //Código Omitido 154 30
155 private void btbuscaractionperformed(java.awt.event.actionevent 156 try { 157 new FormularioBuscar().show(); 158 FormularioBuscar.formulario="Entrada"; 159 } catch (Exception ex) { 160 JOptionPane.showMessageDialog(null, ex); 161 } 162 } 163 164 private void btregistraractionperformed(java.awt.event.actionevent 165 try{ 166 ProdutoDao produtodao = new ProdutoDao(); 167 Movimento movimento = new Movimento(); 168 movimento.settipo(tftipo.gettext()); 169 movimento.setproduto(produtodao.pesquisar(tfproduto.gettext()).get(0)); 170 movimento.setquantidade(double.parsedouble(tfqtde.gettext())); 171 movimento.setdata(tfdata.gettext()); 172 173 MovimentoDao movimentodao = new MovimentoDao(); 174 movimentodao.registarmovimento(movimento); 175 JOptionPane.showMessageDialog(null, "Entrada registada!"); 176 177 tfproduto.settext(null); 178 tfqtde.settext(null); 179 tfdata.settext(null); 180 }catch(exception ex){ 181 JOptionPane.showMessageDialog(null, ex); 182 } 183 } 184 185 private void jbutton1actionperformed(java.awt.event.actionevent 186 dispose(); 187 } 215 236 } 31
Busca de produtos 1 2 import java.util.linkedlist; 3 import java.util.list; 4 import javax.swing.joptionpane; 5 import javax.swing.table.defaulttablemodel; 6 7 /* 8 * To change this template, choose Tools Templates 9 * and open the template in the editor. 10 */ 11 12 /** 13 * 14 * @author Josiel 15 */ 16 public class FormularioBuscar extends javax.swing.jframe { 17 ProdutoDao produtodao = new ProdutoDao(); 32
18 List<Produto> produtos = new LinkedList<>(); 19 public static String formulario=""; 20 /** 21 * Creates new form FormularioBuscar 22 */ 23 public FormularioBuscar() throws Exception{ 24 initcomponents(); 25 } 26 116 117 private void jbutton1actionperformed(java.awt.event.actionevent 118 try{ 119 produtos = produtodao.pesquisar(tfproduto.gettext()); 120 DefaultTableModel tabela = (DefaultTableModel) tbproduto.getmodel(); 121 for(int i=0; i<produtos.size();i++){ 122 tabela.addrow(new Object[]{produtos.get(i).getCodigo(), 123 produtos.get(i).getnome(), 124 produtos.get(i).getfornecedor().getnome(), 125 produtos.get(i).getvalor(), 126 produtos.get(i).getestoque() }); 127 } 128 }catch(exception ex){ 129 JOptionPane.showMessageDialog(null, ex); 130 } 131 } 132 133 private void tbprodutomouseclicked(java.awt.event.mouseevent 134 if(evt.getclickcount()==2){ 135 String nome = tbproduto.getvalueat(tbproduto.getselectedrow(), 1).toString(); 136 if(formulario.equals("entrada")){ 137 FormularioEntrada.tfProduto.setText(nome); 138 }else if(formulario.equals("saída")){ 139 FormularioSaida.tfProduto.setText(nome); 140 } 141 dispose(); 142 } 33
143 } 144 171 172 /* Create and display the form */ 173 java.awt.eventqueue.invokelater(new Runnable() { 174 public void run() { 175 try { 176 new FormularioBuscar().setVisible(true); 177 } catch (Exception ex) { 178 JOptionPane.showMessageDialog(null, ex); 179 } 180 } 181 }); 182 } 183 // Variables declaration - do not modify 184 private javax.swing.jbutton jbutton1; 185 private javax.swing.jlabel jlabel1; 186 private javax.swing.jscrollpane jscrollpane1; 187 private javax.swing.jtable tbproduto; 188 private javax.swing.jtextfield tfproduto; 189 // End of variables declaration 190 } 191 34
Saída 2 import javax.swing.joptionpane; 3 4 /* 5 * To change this template, choose Tools Templates 6 * and open the template in the editor. 7 */ 8 9 /** 10 * 11 * @author Josiel 12 */ 13 public class FormularioSaida extends javax.swing.jframe { 14 15 /** 16 * Creates new form FormularioEntrada 17 */ 18 public FormularioSaida() { 19 initcomponents(); 20 } 21 22 /** 35
153 154 private void btbuscaractionperformed(java.awt.event.actionevent 155 try { 156 new FormularioBuscar().show(); 157 FormularioBuscar.formulario="Saída"; 158 } catch (Exception ex) { 159 JOptionPane.showMessageDialog(null, ex); 160 } 161 } 162 163 private void btregistraractionperformed(java.awt.event.actionevent 164 try { 165 ProdutoDao produtodao = new ProdutoDao(); 166 Movimento movimento = new Movimento(); 167 movimento.settipo(tftipo.gettext()); 168 movimento.setproduto(produtodao.pesquisar(tfproduto.gettext()).get(0)); 169 movimento.setquantidade(double.parsedouble(tfqtde.gettext())); 170 movimento.setdata(tfdata.gettext()); 171 172 MovimentoDao movimentodao = new MovimentoDao(); 173 if (movimentodao.registarmovimento(movimento)) { 174 JOptionPane.showMessageDialog(null, "Saída registada!"); 175 176 tfproduto.settext(null); 177 tfqtde.settext(null); 178 tfdata.settext(null); 179 } else { 180 JOptionPane.showMessageDialog(null, "Estoque insuficiente"); 181 } 182 } catch (Exception ex) { 183 JOptionPane.showMessageDialog(null, ex); 184 } 185 } 186 187 private void jbutton1actionperformed(java.awt.event.actionevent 36
188 dispose(); 189 } 190 37
REFENRÊNCIAS BIBLIOGRÁFICAS TEIXEIRA, Maria. Acesso a Banco de Dados com JDBC (Java Database Connectivity) e o Padrão de Projeto DAO (Data Access Object). Disponível em http://www.ceunes.ufes.br/downloads/2 /mariateixeira-java.introdu%c3%a7%c3%a3o%20a%20banco% 20de%20Dados.pdf. Acessado em 17 de outubro de 2012. CARNEIRO, Davi Luan. Introdução ao pattern DAO. Disponível em http://javafree.uol.com.br/artigo/871452/introducao-ao-pattern- DAO.html. Acessado em 17 de outubro de 2012 38