Advertisement
Guest User

ControlDeStockFrame.java

a guest
May 7th, 2023
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 11.01 KB | Source Code | 0 0
  1. package com.alura.jdbc.view;
  2.  
  3. import java.awt.Color;
  4. import java.awt.Container;
  5. import java.awt.event.ActionEvent;
  6. import java.awt.event.ActionListener;
  7. import java.sql.SQLException;
  8. import java.util.HashMap;
  9. import java.util.Optional;
  10.  
  11. import javax.swing.JButton;
  12. import javax.swing.JComboBox;
  13. import javax.swing.JFrame;
  14. import javax.swing.JLabel;
  15. import javax.swing.JOptionPane;
  16. import javax.swing.JTable;
  17. import javax.swing.JTextField;
  18. import javax.swing.table.DefaultTableModel;
  19. import javax.swing.table.JTableHeader;
  20.  
  21. import com.alura.jdbc.controller.CategoriaController;
  22. import com.alura.jdbc.controller.ProductoController;
  23.  
  24. public class ControlDeStockFrame extends JFrame {
  25.  
  26.     private static final long serialVersionUID = 1L;
  27.  
  28.     private JLabel labelNombre, labelDescripcion, labelCantidad, labelCategoria;
  29.     private JTextField textoNombre, textoDescripcion, textoCantidad;
  30.     private JComboBox<Object> comboCategoria;
  31.     private JButton botonGuardar, botonModificar, botonLimpiar, botonEliminar, botonReporte;
  32.     private JTable tabla;
  33.     private DefaultTableModel modelo; //tabla por defecto para swing
  34.     private ProductoController productoController;
  35.     private CategoriaController categoriaController;
  36.  
  37.     public ControlDeStockFrame() {
  38.         super("Productos");
  39.  
  40.         this.categoriaController = new CategoriaController();
  41.         this.productoController = new ProductoController();
  42.  
  43.         Container container = getContentPane();
  44.         setLayout(null);
  45.  
  46.         configurarCamposDelFormulario(container);
  47.  
  48.         configurarTablaDeContenido(container);
  49.  
  50.         configurarAccionesDelFormulario();
  51.     }
  52.  
  53.     private void configurarTablaDeContenido(Container container) {
  54.         tabla = new JTable();
  55.  
  56.         modelo = (DefaultTableModel) tabla.getModel();
  57.        
  58.         modelo.addColumn("Identificador del Producto");
  59.         modelo.addColumn("Nombre del Producto");
  60.         modelo.addColumn("Descripción del Producto");
  61.         modelo.addColumn("Cantidad");
  62.        
  63.         // Agregar nombres a los encabezados de las columnas
  64.         JTableHeader header = tabla.getTableHeader();
  65.         header.getColumnModel().getColumn(0).setHeaderValue("ID");
  66.         header.getColumnModel().getColumn(1).setHeaderValue("Nombre");
  67.         header.getColumnModel().getColumn(2).setHeaderValue("Descripción");
  68.         header.getColumnModel().getColumn(3).setHeaderValue("Cantidad");
  69.        
  70.         cargarTabla();
  71.  
  72.         tabla.setBounds(10, 205, 760, 280);
  73.        
  74.         botonEliminar = new JButton("Eliminar");
  75.         botonModificar = new JButton("Modificar");
  76.         botonReporte = new JButton("Ver Reporte");
  77.         botonEliminar.setBounds(10, 500, 100, 20);
  78.         botonModificar.setBounds(120, 500, 100, 20);
  79.         botonReporte.setBounds(230, 500, 120, 20);
  80.  
  81.         container.add(tabla);
  82.         container.add(botonEliminar);
  83.         container.add(botonModificar);
  84.         container.add(botonReporte);
  85.  
  86.         setSize(800, 600);
  87.         setVisible(true);
  88.         setLocationRelativeTo(null);
  89.        
  90.     }
  91.  
  92.     private void configurarCamposDelFormulario(Container container) {
  93.         labelNombre = new JLabel("Nombre del Producto");
  94.         labelDescripcion = new JLabel("Descripción del Producto");
  95.         labelCantidad = new JLabel("Cantidad");
  96.         labelCategoria = new JLabel("Categoría del Producto");
  97.  
  98.         labelNombre.setBounds(10, 10, 240, 15);
  99.         labelDescripcion.setBounds(10, 50, 240, 15);
  100.         labelCantidad.setBounds(10, 90, 240, 15);
  101.         labelCategoria.setBounds(10, 130, 240, 15);
  102.  
  103.         labelNombre.setForeground(Color.BLACK);
  104.         labelDescripcion.setForeground(Color.BLACK);
  105.         labelCategoria.setForeground(Color.BLACK);
  106.  
  107.         textoNombre = new JTextField();
  108.         textoDescripcion = new JTextField();
  109.         textoCantidad = new JTextField();
  110.         comboCategoria = new JComboBox<>();
  111.         comboCategoria.addItem("Elige una Categoría");
  112.  
  113.         // TODO
  114.         var categorias = this.categoriaController.listar();
  115.         // categorias.forEach(categoria -> comboCategoria.addItem(categoria));
  116.  
  117.         textoNombre.setBounds(10, 25, 265, 20);
  118.         textoDescripcion.setBounds(10, 65, 265, 20);
  119.         textoCantidad.setBounds(10, 105, 265, 20);
  120.         comboCategoria.setBounds(10, 145, 265, 20);
  121.  
  122.         botonGuardar = new JButton("Guardar");
  123.         botonLimpiar = new JButton("Limpiar");
  124.         botonGuardar.setBounds(10, 175, 80, 20);
  125.         botonLimpiar.setBounds(100, 175, 80, 20);
  126.  
  127.         container.add(labelNombre);
  128.         container.add(labelDescripcion);
  129.         container.add(labelCantidad);
  130.         container.add(labelCategoria);
  131.         container.add(textoNombre);
  132.         container.add(textoDescripcion);
  133.         container.add(textoCantidad);
  134.         container.add(comboCategoria);
  135.         container.add(botonGuardar);
  136.         container.add(botonLimpiar);
  137.     }
  138.  
  139.     private void configurarAccionesDelFormulario() {
  140.         botonGuardar.addActionListener(new ActionListener() {
  141.             public void actionPerformed(ActionEvent e) {
  142.                 guardar();
  143.                 limpiarTabla();
  144.                 cargarTabla();
  145.             }
  146.         });
  147.  
  148.         botonLimpiar.addActionListener(new ActionListener() {
  149.             public void actionPerformed(ActionEvent e) {
  150.                 limpiarFormulario();
  151.             }
  152.         });
  153.  
  154.         botonEliminar.addActionListener(new ActionListener() {
  155.             public void actionPerformed(ActionEvent e) {
  156.                 eliminar();
  157.                 limpiarTabla();
  158.                 cargarTabla();
  159.             }
  160.         });
  161.  
  162.         botonModificar.addActionListener(new ActionListener() {
  163.             public void actionPerformed(ActionEvent e) {
  164.                 modificar();
  165.                 limpiarTabla();
  166.                 cargarTabla();
  167.             }
  168.         });
  169.  
  170.         botonReporte.addActionListener(new ActionListener() {
  171.             public void actionPerformed(ActionEvent e) {
  172.                 abrirReporte();
  173.             }
  174.         });
  175.     }
  176.  
  177.     private void abrirReporte() {
  178.         new ReporteFrame(this);
  179.     }
  180.  
  181.     private void limpiarTabla() {
  182.         modelo.getDataVector().clear();
  183.     }
  184.  
  185.     private boolean tieneFilaElegida() {
  186.         return tabla.getSelectedRowCount() == 0 || tabla.getSelectedColumnCount() == 0;
  187.     }
  188.  
  189.     private void modificar() {
  190.         if (tieneFilaElegida()) {
  191.             JOptionPane.showMessageDialog(this, "Por favor, elije un item");
  192.             return;
  193.         }
  194.  
  195.         Optional.ofNullable(modelo.getValueAt(tabla.getSelectedRow(), tabla.getSelectedColumn()))
  196.                 .ifPresentOrElse(fila -> {
  197.                     Integer id = Integer.valueOf(modelo.getValueAt(tabla.getSelectedRow(), 0).toString());
  198.                     String nombre = modelo.getValueAt(tabla.getSelectedRow(), 1).toString();
  199.                     String descripcion = modelo.getValueAt(tabla.getSelectedRow(), 2).toString();
  200.                     Integer cantidad = Integer.valueOf(modelo.getValueAt(tabla.getSelectedRow(), 3).toString());
  201.                    
  202.                    
  203.                     int filasModificadas;
  204.                    
  205.                     try {
  206.                         filasModificadas = this.productoController.modificar(nombre, descripcion, id,cantidad);
  207.                     } catch (SQLException e) {
  208.                         throw new RuntimeException(e);
  209.                     }
  210.                     JOptionPane.showMessageDialog(this, String.format("%d item modificado con éxito!", filasModificadas));
  211.                 }, () -> JOptionPane.showMessageDialog(this, "Por favor, elije un item"));
  212.     }
  213.  
  214.     private void eliminar() {
  215.         if (tieneFilaElegida()) {
  216.             JOptionPane.showMessageDialog(this, "Por favor, elije un item");
  217.             return;
  218.         }
  219.         //FILA SELECCIONADA: tabla.getSelectedRow(), COLUMNA 0 que refiere al ID   
  220.        
  221.         Optional.ofNullable(modelo.getValueAt(tabla.getSelectedRow(), tabla.getSelectedColumn()))
  222.                 .ifPresentOrElse(fila -> {
  223.                     Integer id = Integer.valueOf(modelo.getValueAt(tabla.getSelectedRow(), 0).toString());
  224.                    
  225.                     int cantidadEliminada;
  226.                    
  227.                     try {
  228.                         cantidadEliminada = this.productoController.eliminar(id);
  229.                     } catch (SQLException e) {
  230.                         throw new RuntimeException(e);
  231.                     }
  232.  
  233.                     modelo.removeRow(tabla.getSelectedRow());
  234.                    
  235.                     JOptionPane.showMessageDialog(this, cantidadEliminada + " item(s) eliminado(s) con éxito!");
  236.                 }, () -> JOptionPane.showMessageDialog(this, "Por favor, elije un item"));
  237.     }
  238.  
  239.     private void cargarTabla() {
  240.        
  241.         try {
  242.             var productos = this.productoController.listar();
  243.             try {
  244.                 /* producto.get("ID") accede al MAP y se refiere a su Key "ID" que indican valores 1 2 3 4 etc;
  245.                 producto.get("NOMBRE") accede al MAP y se refiere a su Key "NOMBRE" que indica nombre de cada producto
  246.                 El foreach realiza esta obtencion de datos con cada una de los objetos de ARRAY */
  247.                 productos.forEach(producto -> modelo.addRow(
  248.                                     new Object[] { producto.get("ID"),
  249.                                     producto.get("NOMBRE"),
  250.                                     producto.get("DESCRIPCION"),
  251.                                     producto.get("CANTIDAD") }));
  252.             } catch (Exception e) {
  253.                 throw new RuntimeException(e);
  254.             }
  255.         } catch (Exception e) {
  256.             throw new RuntimeException(e);
  257.         }
  258.  
  259.     }
  260.  
  261.     private void guardar() {
  262.        
  263.         //Valida si los campos tienen contenido
  264.         if (textoNombre.getText().isBlank() || textoDescripcion.getText().isBlank()) {
  265.             JOptionPane.showMessageDialog(this, "Los campos Nombre y Descripción son requeridos.");
  266.             return;
  267.         }
  268.  
  269.         Integer cantidadInt;
  270.        
  271.         // Valida si el numero es un entero y el limite del entero
  272.         try {
  273.             cantidadInt = Integer.parseInt(textoCantidad.getText());
  274.         } catch (NumberFormatException e) {
  275.             JOptionPane.showMessageDialog(this, String
  276.                     .format("El campo cantidad debe ser numérico dentro del rango %d y %d.", 0, Integer.MAX_VALUE));
  277.             return;
  278.         }
  279.  
  280.         // TODO
  281.         var producto = new HashMap<String,String>();
  282.        
  283.         producto.put("NOMBRE", textoNombre.getText());
  284.         producto.put("DESCRIPCION", textoDescripcion.getText());
  285.         producto.put("CANTIDAD", textoCantidad.getText());
  286.        
  287.         var categoria = comboCategoria.getSelectedItem();
  288.  
  289.         try {
  290.             this.productoController.guardar(producto);
  291.         } catch (SQLException e) {
  292.             throw new RuntimeException(e);
  293.         }
  294.  
  295.         JOptionPane.showMessageDialog(this, "Registrado con éxito!");
  296.  
  297.         this.limpiarFormulario();
  298.        
  299.     }
  300.  
  301.     private void limpiarFormulario() {
  302.         this.textoNombre.setText("");
  303.         this.textoDescripcion.setText("");
  304.         this.textoCantidad.setText("");
  305.         this.comboCategoria.setSelectedIndex(0);
  306.     }
  307.  
  308. }
  309.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement