Advertisement
Guest User

Lista de Produtos com Java: Biblioteca Swing e JDBC

a guest
Jun 20th, 2018
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 10.50 KB | None | 0 0
  1. package exercicio;
  2.  
  3. import java.sql.Connection;
  4. import java.sql.DriverManager;
  5. import java.sql.PreparedStatement;
  6. import java.sql.ResultSet;
  7. import java.sql.SQLException;
  8. import java.util.logging.Level;
  9. import java.util.logging.Logger;
  10.  
  11. /*@author christian moreira
  12. github: github.com/crmon */
  13.  
  14. public class ConnectionFactory {
  15.     private static final String connectionUrl = "jdbc:sqlserver://localhost:1433;"
  16.     +"databaseName=FEIRA;user=usuario;password=111";
  17.    
  18.     public static Connection getConnection(){  
  19.        
  20.         try{    
  21.             Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  
  22.             return DriverManager.getConnection(connectionUrl);
  23.         }
  24.         catch(ClassNotFoundException | SQLException ex){
  25.             throw new RuntimeException("Erro na conexão", ex);
  26.         }
  27.     }
  28.      
  29.     public static void closeConnection(Connection con){
  30.        
  31.         try{  
  32.             if(con != null){
  33.                 con.close();
  34.             }
  35.         }catch(SQLException ex){
  36.             Logger.getLogger(ProdutoDAO.class.getName()).log(Level.SEVERE, null, ex);      
  37.         }
  38.     }
  39.      
  40.    
  41.     public static void closeConnection(Connection con, PreparedStatement stmt){
  42.        
  43.         closeConnection(con);
  44.        
  45.         try{  
  46.             if(stmt != null){
  47.                 stmt.close();
  48.             }
  49.         }catch(SQLException ex){
  50.             Logger.getLogger(ProdutoDAO.class.getName()).log(Level.SEVERE, null, ex);      
  51.         }
  52.     }
  53.    
  54.    
  55.     public static void closeConnection(Connection con, PreparedStatement stmt, ResultSet rs){
  56.        
  57.         closeConnection(con, stmt);
  58.        
  59.         try{  
  60.             if(rs != null){
  61.                 rs.close();
  62.             }
  63.         }catch(SQLException ex){
  64.             Logger.getLogger(ProdutoDAO.class.getName()).log(Level.SEVERE, null, ex);      
  65.         }
  66.     }
  67.    
  68. }
  69.  
  70. /* ================================= Inicio Produto ================================= */
  71.  
  72. package exercicio;
  73.  
  74. /*@author christian moreira
  75. github: github.com/crmon */
  76.  
  77. public class Produto {
  78.    
  79.     private int cod;
  80.     private String nome;
  81.  
  82.     public Produto() {}
  83.  
  84.     public Produto(int cod, String nome) {
  85.         this.cod = cod;
  86.         this.nome = nome;
  87.     }
  88.  
  89.     public Produto(String nome) {
  90.         this.nome = nome;
  91.     }
  92.  
  93.     public int getCod() {
  94.         return cod;
  95.     }
  96.    
  97.     public void setCod(int cod) {
  98.         this.cod = cod;
  99.     }
  100.  
  101.     public String getNome() {
  102.         return nome;
  103.     }
  104.  
  105.     public void setNome(String nome) {
  106.         this.nome = nome;
  107.     }
  108.    
  109. }
  110.  
  111. /* ================================= Inicio ProdutoDAO ================================= */
  112.  
  113. package exercicio;
  114.  
  115. import java.sql.Connection;
  116. import java.sql.PreparedStatement;
  117. import java.sql.ResultSet;
  118. import java.sql.SQLException;
  119. import java.util.ArrayList;
  120. import java.util.logging.Level;
  121. import java.util.logging.Logger;
  122.  
  123. /*@author christian moreira
  124. github: github.com/crmon */
  125.  
  126. public class ProdutoDAO {
  127.        
  128.     public void adicionar(Produto produto){
  129.        
  130.         Connection con = ConnectionFactory.getConnection();
  131.         PreparedStatement stmt = null;  
  132.  
  133.         try{
  134.             stmt = con.prepareStatement("INSERT INTO PRODUTO(NOME) VALUES(?)");
  135.             stmt.setString(1, produto.getNome());
  136.             stmt.execute();
  137.         }
  138.         catch(SQLException ex) {
  139.             Logger.getLogger(ProdutoDAO.class.getName()).log(Level.SEVERE, null, ex);      
  140.         }finally{
  141.             ConnectionFactory.closeConnection(con, stmt);
  142.         }        
  143.     }
  144.    
  145.     public ArrayList<Produto> listar(){
  146.  
  147.         Connection con = ConnectionFactory.getConnection();
  148.         PreparedStatement stmt = null;
  149.         ResultSet rs = null;
  150.        
  151.         ArrayList<Produto> produtos = new ArrayList<>();
  152.        
  153.         try{
  154.             stmt = con.prepareStatement("SELECT * FROM PRODUTO");
  155.             rs = stmt.executeQuery();
  156.            
  157.             while(rs.next()){
  158.                 Produto produto = new Produto(rs.getInt("COD"), rs.getString("NOME"));
  159.                 produtos.add(produto);
  160.             }
  161.         }
  162.         catch(SQLException ex){
  163.             Logger.getLogger(ProdutoDAO.class.getName()).log(Level.SEVERE, null, ex);      
  164.         }
  165.         finally{
  166.             ConnectionFactory.closeConnection(con, stmt, rs);
  167.         }
  168.        
  169.         return produtos;
  170.     }
  171.      
  172.     public void alterar(Produto produto){
  173.        
  174.         Connection con = ConnectionFactory.getConnection();
  175.         PreparedStatement stmt = null;    
  176.  
  177.         try{
  178.             stmt = con.prepareStatement("UPDATE PRODUTO SET NOME = ? WHERE COD = ?");
  179.             stmt.setString(1, produto.getNome());
  180.             stmt.setInt(2, produto.getCod());
  181.             stmt.executeUpdate();
  182.             stmt.close();
  183.         }
  184.         catch(SQLException ex) {
  185.             Logger.getLogger(ProdutoDAO.class.getName()).log(Level.SEVERE, null, ex);      
  186.         }finally{
  187.             ConnectionFactory.closeConnection(con, stmt);
  188.         }        
  189.     }
  190.    
  191.     public void deletar(Produto produto){
  192.        
  193.         Connection con = ConnectionFactory.getConnection();
  194.         PreparedStatement stmt = null;    
  195.  
  196.         try{
  197.             stmt = con.prepareStatement("DELETE FROM PRODUTO WHERE COD = ?");
  198.             stmt.setInt(1, produto.getCod());
  199.             stmt.executeUpdate();
  200.             stmt.close();
  201.         }
  202.         catch(SQLException ex) {
  203.             Logger.getLogger(ProdutoDAO.class.getName()).log(Level.SEVERE, null, ex);      
  204.         }finally{
  205.             ConnectionFactory.closeConnection(con, stmt);
  206.         }        
  207.     }
  208.    
  209.     public void limpar(){
  210.        
  211.         Connection con = ConnectionFactory.getConnection();
  212.         PreparedStatement stmt = null;    
  213.  
  214.         try{
  215.             stmt = con.prepareStatement("DELETE FROM PRODUTO");
  216.             stmt.executeUpdate();
  217.             stmt.close();
  218.         }
  219.         catch(SQLException ex) {
  220.             Logger.getLogger(ProdutoDAO.class.getName()).log(Level.SEVERE, null, ex);      
  221.         }finally{
  222.             ConnectionFactory.closeConnection(con, stmt);
  223.         }        
  224.     }
  225.  
  226. }
  227.  
  228. /* ================================= Inicio MyList ================================= */
  229.  
  230.  
  231. package exercicio;
  232.  
  233. import exercicio.ProdutoDAO;
  234. import java.awt.BorderLayout;
  235. import java.awt.Color;
  236. import java.awt.FlowLayout;
  237. import java.awt.Font;
  238. import java.sql.SQLException;
  239. import java.util.ArrayList;
  240. import javax.swing.DefaultListCellRenderer;
  241. import javax.swing.DefaultListModel;
  242. import javax.swing.JButton;
  243. import javax.swing.JFrame;
  244. import javax.swing.JLabel;
  245. import javax.swing.JList;
  246. import javax.swing.JPanel;
  247. import javax.swing.JTextField;
  248.  
  249. /*@author christian moreira
  250. github: github.com/crmon */
  251.  
  252. public class MyList extends JFrame {
  253.  
  254.     private JList<String> controllerLista;
  255.     private DefaultListModel<String> modelLista;
  256.     private DefaultListCellRenderer viewLista;
  257.     private JPanel pnlCentral;
  258.     private JTextField txtTarefa;
  259.     private JButton btnAdicionar, btnLimpar, btnDeletar, btnAlterar;
  260.    
  261.     private ProdutoDAO produtoDAO = new ProdutoDAO();
  262.     private int index;
  263.  
  264.     public MyList() {
  265.         super("My List v1.0");
  266.         setLayout(new BorderLayout());
  267.         viewLista = new DefaultListCellRenderer();
  268.         modelLista = new DefaultListModel();
  269.         controllerLista = new JList<String>(modelLista);
  270.  
  271.         pnlCentral = new JPanel(new FlowLayout());
  272.         btnAdicionar = new JButton("Adicionar");
  273.         btnLimpar = new JButton("Limpar");
  274.         btnDeletar = new JButton("Deletar");
  275.         btnAlterar = new JButton("Alterar");
  276.         txtTarefa = new JTextField(20);
  277.        
  278.         produtoDAO = new ProdutoDAO();
  279.     }
  280.  
  281.     public void init() {
  282.         setSize(640, 480);
  283.         setLocationRelativeTo(null);
  284.  
  285.         JLabel lblTitulo = new JLabel("Minha Lista");
  286.  
  287.         getContentPane().add(lblTitulo, BorderLayout.NORTH);
  288.         getContentPane().add(controllerLista, BorderLayout.CENTER);
  289.         getContentPane().add(pnlCentral, BorderLayout.SOUTH);
  290.         pnlCentral.add(txtTarefa);
  291.         pnlCentral.add(btnAdicionar);
  292.         pnlCentral.add(btnLimpar);
  293.         pnlCentral.add(btnDeletar);
  294.         pnlCentral.add(btnAlterar);
  295.        
  296.         atualizarModelList();
  297.        
  298.         controllerLista.setBackground(Color.black);
  299.         controllerLista.setFont(new Font("Verdana", Font.BOLD, 15));
  300.         controllerLista.setForeground(Color.white);
  301.         lblTitulo.setFont(new Font("Verdana", Font.BOLD, 30));
  302.         lblTitulo.setForeground(Color.black);
  303.        
  304.        
  305.        
  306.         controllerLista.addListSelectionListener((lse) -> {
  307.             txtTarefa.setText(controllerLista.getSelectedValue());
  308.             index = controllerLista.getSelectedIndex();
  309.  
  310.            
  311.         });
  312.        
  313.  
  314.         btnAdicionar.addActionListener((ae) -> {
  315.        
  316.             Produto produto = new Produto();
  317.             produto.setNome(txtTarefa.getText());
  318.             produtoDAO.adicionar(produto);
  319.             atualizarModelList();
  320.             txtTarefa.setText("");
  321.         });
  322.  
  323.         btnLimpar.addActionListener((ae) -> {
  324.            
  325.             produtoDAO.limpar();
  326.             atualizarModelList();
  327.             txtTarefa.setText("");
  328.         });
  329.  
  330.         btnDeletar.addActionListener((ae) -> {
  331.                  
  332.             produtoDAO.deletar(produtoDAO.listar().get(index));
  333.             atualizarModelList();
  334.             txtTarefa.setText("");
  335.         });
  336.  
  337.         btnAlterar.addActionListener((ae) -> {
  338.            
  339.             if(txtTarefa.getText() != null ){
  340.        
  341.                 ArrayList<Produto> produtos = produtoDAO.listar();
  342.                 Produto produto = new Produto(produtos.get(index).getCod(), txtTarefa.getText());
  343.                 produtoDAO.alterar(produto);
  344.                 atualizarModelList();
  345.                 txtTarefa.setText("");
  346.             }
  347.         });
  348.    
  349.        
  350.         setDefaultCloseOperation(EXIT_ON_CLOSE);
  351.         setVisible(true);
  352.     }
  353.  
  354.     public static void main(String[] args) {
  355.         new MyList().init();
  356.     }
  357.    
  358.    
  359.     public void atualizarModelList(){
  360.        
  361.         modelLista.setSize(0);
  362.        
  363.         for(Produto p : produtoDAO.listar()){
  364.             modelLista.addElement(p.getNome());
  365.         }
  366.     }
  367.  
  368. }
  369.  
  370.  
  371. /* ================================= FIM MyList ================================= */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement