Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.alura.jdbc.view;
- import java.awt.Color;
- import java.awt.Container;
- import java.awt.event.ActionEvent;
- import java.awt.event.ActionListener;
- import java.sql.SQLException;
- import java.util.HashMap;
- import java.util.Optional;
- import javax.swing.JButton;
- import javax.swing.JComboBox;
- import javax.swing.JFrame;
- import javax.swing.JLabel;
- import javax.swing.JOptionPane;
- import javax.swing.JTable;
- import javax.swing.JTextField;
- import javax.swing.table.DefaultTableModel;
- import javax.swing.table.JTableHeader;
- import com.alura.jdbc.controller.CategoriaController;
- import com.alura.jdbc.controller.ProductoController;
- public class ControlDeStockFrame extends JFrame {
- private static final long serialVersionUID = 1L;
- private JLabel labelNombre, labelDescripcion, labelCantidad, labelCategoria;
- private JTextField textoNombre, textoDescripcion, textoCantidad;
- private JComboBox<Object> comboCategoria;
- private JButton botonGuardar, botonModificar, botonLimpiar, botonEliminar, botonReporte;
- private JTable tabla;
- private DefaultTableModel modelo; //tabla por defecto para swing
- private ProductoController productoController;
- private CategoriaController categoriaController;
- public ControlDeStockFrame() {
- super("Productos");
- this.categoriaController = new CategoriaController();
- this.productoController = new ProductoController();
- Container container = getContentPane();
- setLayout(null);
- configurarCamposDelFormulario(container);
- configurarTablaDeContenido(container);
- configurarAccionesDelFormulario();
- }
- private void configurarTablaDeContenido(Container container) {
- tabla = new JTable();
- modelo = (DefaultTableModel) tabla.getModel();
- modelo.addColumn("Identificador del Producto");
- modelo.addColumn("Nombre del Producto");
- modelo.addColumn("Descripción del Producto");
- modelo.addColumn("Cantidad");
- // Agregar nombres a los encabezados de las columnas
- JTableHeader header = tabla.getTableHeader();
- header.getColumnModel().getColumn(0).setHeaderValue("ID");
- header.getColumnModel().getColumn(1).setHeaderValue("Nombre");
- header.getColumnModel().getColumn(2).setHeaderValue("Descripción");
- header.getColumnModel().getColumn(3).setHeaderValue("Cantidad");
- cargarTabla();
- tabla.setBounds(10, 205, 760, 280);
- botonEliminar = new JButton("Eliminar");
- botonModificar = new JButton("Modificar");
- botonReporte = new JButton("Ver Reporte");
- botonEliminar.setBounds(10, 500, 100, 20);
- botonModificar.setBounds(120, 500, 100, 20);
- botonReporte.setBounds(230, 500, 120, 20);
- container.add(tabla);
- container.add(botonEliminar);
- container.add(botonModificar);
- container.add(botonReporte);
- setSize(800, 600);
- setVisible(true);
- setLocationRelativeTo(null);
- }
- private void configurarCamposDelFormulario(Container container) {
- labelNombre = new JLabel("Nombre del Producto");
- labelDescripcion = new JLabel("Descripción del Producto");
- labelCantidad = new JLabel("Cantidad");
- labelCategoria = new JLabel("Categoría del Producto");
- labelNombre.setBounds(10, 10, 240, 15);
- labelDescripcion.setBounds(10, 50, 240, 15);
- labelCantidad.setBounds(10, 90, 240, 15);
- labelCategoria.setBounds(10, 130, 240, 15);
- labelNombre.setForeground(Color.BLACK);
- labelDescripcion.setForeground(Color.BLACK);
- labelCategoria.setForeground(Color.BLACK);
- textoNombre = new JTextField();
- textoDescripcion = new JTextField();
- textoCantidad = new JTextField();
- comboCategoria = new JComboBox<>();
- comboCategoria.addItem("Elige una Categoría");
- // TODO
- var categorias = this.categoriaController.listar();
- // categorias.forEach(categoria -> comboCategoria.addItem(categoria));
- textoNombre.setBounds(10, 25, 265, 20);
- textoDescripcion.setBounds(10, 65, 265, 20);
- textoCantidad.setBounds(10, 105, 265, 20);
- comboCategoria.setBounds(10, 145, 265, 20);
- botonGuardar = new JButton("Guardar");
- botonLimpiar = new JButton("Limpiar");
- botonGuardar.setBounds(10, 175, 80, 20);
- botonLimpiar.setBounds(100, 175, 80, 20);
- container.add(labelNombre);
- container.add(labelDescripcion);
- container.add(labelCantidad);
- container.add(labelCategoria);
- container.add(textoNombre);
- container.add(textoDescripcion);
- container.add(textoCantidad);
- container.add(comboCategoria);
- container.add(botonGuardar);
- container.add(botonLimpiar);
- }
- private void configurarAccionesDelFormulario() {
- botonGuardar.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- guardar();
- limpiarTabla();
- cargarTabla();
- }
- });
- botonLimpiar.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- limpiarFormulario();
- }
- });
- botonEliminar.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- eliminar();
- limpiarTabla();
- cargarTabla();
- }
- });
- botonModificar.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- modificar();
- limpiarTabla();
- cargarTabla();
- }
- });
- botonReporte.addActionListener(new ActionListener() {
- public void actionPerformed(ActionEvent e) {
- abrirReporte();
- }
- });
- }
- private void abrirReporte() {
- new ReporteFrame(this);
- }
- private void limpiarTabla() {
- modelo.getDataVector().clear();
- }
- private boolean tieneFilaElegida() {
- return tabla.getSelectedRowCount() == 0 || tabla.getSelectedColumnCount() == 0;
- }
- private void modificar() {
- if (tieneFilaElegida()) {
- JOptionPane.showMessageDialog(this, "Por favor, elije un item");
- return;
- }
- Optional.ofNullable(modelo.getValueAt(tabla.getSelectedRow(), tabla.getSelectedColumn()))
- .ifPresentOrElse(fila -> {
- Integer id = Integer.valueOf(modelo.getValueAt(tabla.getSelectedRow(), 0).toString());
- String nombre = modelo.getValueAt(tabla.getSelectedRow(), 1).toString();
- String descripcion = modelo.getValueAt(tabla.getSelectedRow(), 2).toString();
- Integer cantidad = Integer.valueOf(modelo.getValueAt(tabla.getSelectedRow(), 3).toString());
- int filasModificadas;
- try {
- filasModificadas = this.productoController.modificar(nombre, descripcion, id,cantidad);
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- JOptionPane.showMessageDialog(this, String.format("%d item modificado con éxito!", filasModificadas));
- }, () -> JOptionPane.showMessageDialog(this, "Por favor, elije un item"));
- }
- private void eliminar() {
- if (tieneFilaElegida()) {
- JOptionPane.showMessageDialog(this, "Por favor, elije un item");
- return;
- }
- //FILA SELECCIONADA: tabla.getSelectedRow(), COLUMNA 0 que refiere al ID
- Optional.ofNullable(modelo.getValueAt(tabla.getSelectedRow(), tabla.getSelectedColumn()))
- .ifPresentOrElse(fila -> {
- Integer id = Integer.valueOf(modelo.getValueAt(tabla.getSelectedRow(), 0).toString());
- int cantidadEliminada;
- try {
- cantidadEliminada = this.productoController.eliminar(id);
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- modelo.removeRow(tabla.getSelectedRow());
- JOptionPane.showMessageDialog(this, cantidadEliminada + " item(s) eliminado(s) con éxito!");
- }, () -> JOptionPane.showMessageDialog(this, "Por favor, elije un item"));
- }
- private void cargarTabla() {
- try {
- var productos = this.productoController.listar();
- try {
- /* producto.get("ID") accede al MAP y se refiere a su Key "ID" que indican valores 1 2 3 4 etc;
- producto.get("NOMBRE") accede al MAP y se refiere a su Key "NOMBRE" que indica nombre de cada producto
- El foreach realiza esta obtencion de datos con cada una de los objetos de ARRAY */
- productos.forEach(producto -> modelo.addRow(
- new Object[] { producto.get("ID"),
- producto.get("NOMBRE"),
- producto.get("DESCRIPCION"),
- producto.get("CANTIDAD") }));
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
- private void guardar() {
- //Valida si los campos tienen contenido
- if (textoNombre.getText().isBlank() || textoDescripcion.getText().isBlank()) {
- JOptionPane.showMessageDialog(this, "Los campos Nombre y Descripción son requeridos.");
- return;
- }
- Integer cantidadInt;
- // Valida si el numero es un entero y el limite del entero
- try {
- cantidadInt = Integer.parseInt(textoCantidad.getText());
- } catch (NumberFormatException e) {
- JOptionPane.showMessageDialog(this, String
- .format("El campo cantidad debe ser numérico dentro del rango %d y %d.", 0, Integer.MAX_VALUE));
- return;
- }
- // TODO
- var producto = new HashMap<String,String>();
- producto.put("NOMBRE", textoNombre.getText());
- producto.put("DESCRIPCION", textoDescripcion.getText());
- producto.put("CANTIDAD", textoCantidad.getText());
- var categoria = comboCategoria.getSelectedItem();
- try {
- this.productoController.guardar(producto);
- } catch (SQLException e) {
- throw new RuntimeException(e);
- }
- JOptionPane.showMessageDialog(this, "Registrado con éxito!");
- this.limpiarFormulario();
- }
- private void limpiarFormulario() {
- this.textoNombre.setText("");
- this.textoDescripcion.setText("");
- this.textoCantidad.setText("");
- this.comboCategoria.setSelectedIndex(0);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement