Вы находитесь на странице: 1из 43

JOSIEL S.

MOURA

MANIPULAO DE BANCO DE
DADOS UTILIZANDO
INTERFACE GRFICA

ORIENTADO A PROJETO: CONTROLE DE ESTOQUE


2012



JOSIEL S. MOURA






MANIPULAO DE BANCO DE
DADOS UTILIZANDO
INTERFACE GRFICA




ORIENTADO A PROJETO: CONTROLE DE ESTOQUE






2012
Sumrio
INTRODUO ............................................................................ 3
PADRO DAO ............................................................................ 4
ESTUDO DE CASO .................................................................... 6
Banco de Dados ...................................................................... 6
Entidade................................................................................... 7
Fornecedor ........................................................................... 7
Produto ................................................................................. 8
Movimento ............................................................................ 9
Dao ........................................................................................ 11
Conexo ............................................................................. 11
Fornecedor ......................................................................... 12
Produto ............................................................................... 13
Movimento .......................................................................... 15
Formulrios ............................................................................ 17
Principal ................................................................................. 17
Fornecedor ......................................................................... 18
Produto ............................................................................... 24
Entrada ............................................................................... 30
Busca de produtos.............................................................. 32
Sada .................................................................................. 35


REFENRNCIAS BIBLIOGRFICAS ........................................ 38

3

INTRODUO

A ideia de padres foi apresentada por Christopher
Alexander em 1977 no contexto de Arquitetura (de prdios e
cidades).
Cada padro descreve um problema que ocorre
repetidamente, de novo e de novo, em nosso ambiente, e ento
descreve a parte central da soluo para aquele problema de
uma forma que voc pode usar esta soluo um milho de
vezes, sem nunca implement-la duas vezes da mesma forma.
Um padro de projeto uma espcie de gabarito para
como resolver um problema, ou melhor dizendo, uma soluo
elegante na resoluo de problemas.

4

PADRO DAO

A maioria das aplicaes 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 lgica de persistncia com a lgica de aplicao
cria uma dependncia direta entre a implementao da aplicao
e do armazenamento persistente. Tal dependncia de cdigo nos
componentes torna difcil e maante migrar a aplicao de um
tipo de fonte de dados para outro.
Quando as fontes de dados so 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 conexo 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 aplicao. Semelhantemente, deve
saber como pegar os objetos, converter em instrues SQL e
5

mandar para o banco de dados relacional. assim que um DAO
trabalha.
O principal objetivo de um DAO encapsular o acesso e a
manipulao de dados em uma camada separada.

6

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 movimentao (entrada e sada) desses
produtos.

Figura 1: Diagrama de entidade e relacionamento
7

Entidade
A entidade a representao da tabela do banco de
dados em nosso aplicativo. Deve ser criados os mtodos gets e
sets para implementar o encapsulamento de nosso cdigo.
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() {
8

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;
9

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;
10

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
11

44 public void setProduto(Produto produto) {
45 this.produto = produto;
46 }
47
48 }


Dao
Primeiramente precisamos de uma classe que estabelea
a conexo com o banco de dados:
Conexo
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


12

Vamos criar uma classe AlunoDAO que possui os
mtodos 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));
13

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();
14

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
15

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
16

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 }




17

Formulrios
Principal



Abaixo temos os eventos para os botes
120 private void
jbFornecedorActionPerformed(java.awt.event.ActionEvent evt) {
121 try {
122 new FormularioFornecedor().show();
123 } catch (Exception ex) {
124 JOptionPane.showMessageDialog(null, ex);
125 }
18

126 }
127
128 private void jbProdutoActionPerformed(java.awt.event.ActionEvent
evt) {
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
evt) {
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
evt) {
145 try {
146 new FormularioSaida().show();
147 } catch (Exception ex) {
148 JOptionPane.showMessageDialog(null, ex);
149 }
150 }

Figura 2: Formulrio principal

Fornecedor

19





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
20

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());
21

50 tfCnpj.setText(f.getCnpj());
51 }
52
53 //Cdigo omitido
249
250 private void
btCadastrarActionPerformed(java.awt.event.ActionEvent evt) {
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
evt) {
262 dispose();
263 }
264
265 private void
btPesquisarActionPerformed(java.awt.event.ActionEvent evt) {
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
evt) {
276 if (posicao < fornecedores.size() - 1) {
277 posicao++;
278 setFornecedor(fornecedores.get(posicao));
279 }
22

280 }
281
282 private void btAnteriorActionPerformed(java.awt.event.ActionEvent
evt) {
283 if (posicao > 0) {
284 posicao--;
285 setFornecedor(fornecedores.get(posicao));
286 }
287 }
288
289 private void btPrimeiroActionPerformed(java.awt.event.ActionEvent
evt) {
290 posicao = 0;
291 setFornecedor(fornecedores.get(posicao));
292 }
293
294 private void btUltimoActionPerformed(java.awt.event.ActionEvent
evt) {
295 posicao = fornecedores.size() - 1;
296 setFornecedor(fornecedores.get(posicao));
297 }
298
299 private void btAlterarActionPerformed(java.awt.event.ActionEvent
evt) {
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
evt) {
311 try {
312 getFornecedor();
313 fornecedorDao.excluir(fornecedor.getId());
314 JOptionPane.showMessageDialog(null, "Excluido com
23

sucesso!");
315 limparCampos();
316 } catch (Exception ex) {
317 JOptionPane.showMessageDialog(null, ex);
318 }
319 }
320
321 private void btNovoActionPerformed(java.awt.event.ActionEvent
evt) {
322 limparCampos();
323 }
324
325 //Cdigo 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;
24

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 /*
25

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
26

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 //Cdigo omitido
280
281 private void
btCadastrarActionPerformed(java.awt.event.ActionEvent evt) {
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
evt) {
293 dispose();
294 }
295
296 private void
27

btPesquisarActionPerformed(java.awt.event.ActionEvent evt) {
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
evt) {
307 if (posicao < produtos.size() - 1) {
308 posicao++;
309 setFornecedor(produtos.get(posicao));
310 }
311 }
312
313 private void btAnteriorActionPerformed(java.awt.event.ActionEvent
evt) {
314 if (posicao > 0) {
315 posicao--;
316 setFornecedor(produtos.get(posicao));
317 }
318 }
319
320 private void btPrimeiroActionPerformed(java.awt.event.ActionEvent
evt) {
321 posicao = 0;
322 setFornecedor(produtos.get(posicao));
323 }
324
325 private void btUltimoActionPerformed(java.awt.event.ActionEvent
evt) {
326 posicao = produtos.size() - 1;
327 setFornecedor(produtos.get(posicao));
328 }
329
330 private void btAlterarActionPerformed(java.awt.event.ActionEvent
evt) {
28

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
evt) {
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
evt) {
353 limparCampos();
354 }
355
356 //Cdigo 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 });
29

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 }
30


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 //Cdigo Omitido
154
31

155 private void btBuscarActionPerformed(java.awt.event.ActionEvent
evt) {
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 evt) {
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
evt) {
186 dispose();
187 }
215
236 }
32


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();
33

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
evt) {
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
evt) {
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("Sada")){
139 FormularioSaida.tfProduto.setText(nome);
140 }
141 dispose();
142 }
34

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
35



Sada

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 /**
36

153
154 private void btBuscarActionPerformed(java.awt.event.ActionEvent
evt) {
155 try {
156 new FormularioBuscar().show();
157 FormularioBuscar.formulario="Sada";
158 } catch (Exception ex) {
159 JOptionPane.showMessageDialog(null, ex);
160 }
161 }
162
163 private void
btRegistrarActionPerformed(java.awt.event.ActionEvent evt) {
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, "Sada 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
evt) {
37

188 dispose();
189 }
190

38

REFENRNCIAS BIBLIOGRFICAS

TEIXEIRA, Maria. Acesso a Banco de Dados com JDBC (Java
Database Connectivity) e o Padro de Projeto DAO (Data Access
Object). Disponvel 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. Introduo ao pattern DAO. Disponvel em
http://javafree.uol.com.br/artigo/871452/Introducao-ao-pattern-
DAO.html. Acessado em 17 de outubro de 2012

Вам также может понравиться