com.app.mantenimiento.Clientes.java Source code

Java tutorial

Introduction

Here is the source code for com.app.mantenimiento.Clientes.java

Source

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.app.mantenimiento;

import com.entidades.MtCiudades;
import com.entidades.MtClientes;
import com.entidades.MtDepartamentos;
import com.entidades.MtEstcivil;
import java.util.List;
import javax.swing.table.DefaultTableModel;
import org.hibernate.Session;
import util.HibernateUtil;

import com.entidades.MtSexos;
import com.entidades.MtTipoDocumentos;
import com.entidades.MtTiposClientes;
import java.awt.HeadlessException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Date;
import javax.swing.JOptionPane;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;
import net.sf.jasperreports.view.JasperViewer;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import com.app.seguridad.Permisos;

/**
 * @author Carlos Patino
 */
public class Clientes extends javax.swing.JDialog {

    private String usuario;
    private String origen;
    private String formulario;

    /**
     * Creates new form Formularios
     */
    public Clientes(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        hibernateSession();
        arranque();
    }

    public Clientes(String user) {
        setLocationRelativeTo(null);
        initComponents();
        hibernateSession();
        this.setUsuario(user);
        this.formulario = this.getClass().getSimpleName();
        this.cmdGuardar.setEnabled(false);
        arranque();
    }

    private Session st;
    private DefaultTableModel model;

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        cmdNuevo = new javax.swing.JButton();
        cmdGuardar = new javax.swing.JButton();
        cmdEditar = new javax.swing.JButton();
        cmdBorrar = new javax.swing.JButton();
        cmdCancelar = new javax.swing.JButton();
        cmdReporte = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        txtNroDocum = new javax.swing.JTextField();
        txtNombre = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txtDireccion = new javax.swing.JTextField();
        txtTelefono = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        txtCelular = new javax.swing.JTextField();
        jLabel8 = new javax.swing.JLabel();
        txtEmail = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        cboLocalidad = new javax.swing.JComboBox();
        jLabel11 = new javax.swing.JLabel();
        jLabel12 = new javax.swing.JLabel();
        jLabel13 = new javax.swing.JLabel();
        jLabel14 = new javax.swing.JLabel();
        cboTipoDoc = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        cboTipoCli = new javax.swing.JComboBox();
        cboEstCivil = new javax.swing.JComboBox();
        jLabel15 = new javax.swing.JLabel();
        cboSexo = new javax.swing.JComboBox();
        cboEstado = new javax.swing.JComboBox();
        txtPais = new javax.swing.JTextField();
        txtDepto = new javax.swing.JTextField();
        txtCodTit = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabClientes = new javax.swing.JTable();
        cmdCerrar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Mantenimiento de Clientes - KARU v1.0");
        setMinimumSize(new java.awt.Dimension(530, 650));
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });
        getContentPane().setLayout(null);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Matenimiento de Clientes");
        getContentPane().add(jLabel1);
        jLabel1.setBounds(20, 10, 490, 30);

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel1.setLayout(null);

        cmdNuevo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/imagenes/New.png"))); // NOI18N
        cmdNuevo.setToolTipText("Nuevo");
        cmdNuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdNuevoActionPerformed(evt);
            }
        });
        jPanel1.add(cmdNuevo);
        cmdNuevo.setBounds(12, 3, 33, 33);

        cmdGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/imagenes/Save.png"))); // NOI18N
        cmdGuardar.setToolTipText("Guardar");
        cmdGuardar.setEnabled(false);
        cmdGuardar.setMaximumSize(new java.awt.Dimension(91, 33));
        cmdGuardar.setMinimumSize(new java.awt.Dimension(91, 33));
        cmdGuardar.setPreferredSize(new java.awt.Dimension(91, 33));
        cmdGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdGuardarActionPerformed(evt);
            }
        });
        jPanel1.add(cmdGuardar);
        cmdGuardar.setBounds(51, 3, 33, 33);

        cmdEditar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/imagenes/edit.png"))); // NOI18N
        cmdEditar.setToolTipText("Editar");
        cmdEditar.setMaximumSize(new java.awt.Dimension(91, 33));
        cmdEditar.setMinimumSize(new java.awt.Dimension(91, 33));
        cmdEditar.setPreferredSize(new java.awt.Dimension(91, 33));
        cmdEditar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdEditarActionPerformed(evt);
            }
        });
        jPanel1.add(cmdEditar);
        cmdEditar.setBounds(90, 3, 33, 33);

        cmdBorrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/imagenes/Trashcan_empty.png"))); // NOI18N
        cmdBorrar.setToolTipText("Borrar");
        cmdBorrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdBorrarActionPerformed(evt);
            }
        });
        jPanel1.add(cmdBorrar);
        cmdBorrar.setBounds(129, 3, 33, 33);

        cmdCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/imagenes/cancel32.png"))); // NOI18N
        cmdCancelar.setToolTipText("Cancelar");
        cmdCancelar.setMaximumSize(new java.awt.Dimension(91, 33));
        cmdCancelar.setMinimumSize(new java.awt.Dimension(91, 33));
        cmdCancelar.setPreferredSize(new java.awt.Dimension(91, 33));
        cmdCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdCancelarActionPerformed(evt);
            }
        });
        jPanel1.add(cmdCancelar);
        cmdCancelar.setBounds(170, 3, 33, 33);

        cmdReporte.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/imagenes/Tasks.png"))); // NOI18N
        cmdReporte.setToolTipText("Informe");
        cmdReporte.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdReporteActionPerformed(evt);
            }
        });
        jPanel1.add(cmdReporte);
        cmdReporte.setBounds(210, 3, 35, 33);

        getContentPane().add(jPanel1);
        jPanel1.setBounds(20, 50, 490, 40);

        jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel2.setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        jPanel2.setLayout(null);

        txtNroDocum.setEditable(false);
        txtNroDocum.setBackground(new java.awt.Color(255, 255, 255));
        txtNroDocum.setPreferredSize(new java.awt.Dimension(8, 20));
        txtNroDocum.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusLost(java.awt.event.FocusEvent evt) {
                txtNroDocumFocusLost(evt);
            }
        });
        jPanel2.add(txtNroDocum);
        txtNroDocum.setBounds(120, 50, 140, 25);

        txtNombre.setEditable(false);
        txtNombre.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.add(txtNombre);
        txtNombre.setBounds(120, 80, 350, 25);

        jLabel5.setText("Cdigo");
        jPanel2.add(jLabel5);
        jLabel5.setBounds(10, 50, 100, 25);

        jLabel6.setText("Nombre Titular");
        jPanel2.add(jLabel6);
        jLabel6.setBounds(10, 80, 110, 25);

        jLabel7.setText("Estado Civil");
        jPanel2.add(jLabel7);
        jLabel7.setBounds(10, 110, 110, 25);

        txtDireccion.setEditable(false);
        txtDireccion.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.add(txtDireccion);
        txtDireccion.setBounds(120, 140, 350, 25);

        txtTelefono.setEditable(false);
        txtTelefono.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.add(txtTelefono);
        txtTelefono.setBounds(120, 230, 120, 25);

        jLabel2.setText("Direccin");
        jPanel2.add(jLabel2);
        jLabel2.setBounds(10, 140, 110, 25);

        jLabel3.setText("Telfono");
        jPanel2.add(jLabel3);
        jLabel3.setBounds(10, 230, 90, 25);

        txtCelular.setEditable(false);
        txtCelular.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.add(txtCelular);
        txtCelular.setBounds(300, 230, 170, 25);

        jLabel8.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel8.setText("Celular");
        jPanel2.add(jLabel8);
        jLabel8.setBounds(230, 230, 60, 25);

        txtEmail.setEditable(false);
        txtEmail.setBackground(new java.awt.Color(255, 255, 255));
        jPanel2.add(txtEmail);
        txtEmail.setBounds(120, 260, 350, 26);

        jLabel9.setText("Email");
        jPanel2.add(jLabel9);
        jLabel9.setBounds(10, 260, 100, 25);

        jLabel10.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel10.setText("Activo?");
        jPanel2.add(jLabel10);
        jLabel10.setBounds(270, 20, 50, 25);

        cboLocalidad.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                cboLocalidadMouseClicked(evt);
            }
        });
        jPanel2.add(cboLocalidad);
        cboLocalidad.setBounds(120, 170, 250, 25);

        jLabel11.setText("Localidad");
        jPanel2.add(jLabel11);
        jLabel11.setBounds(10, 170, 110, 25);

        jLabel12.setText("Departamento");
        jPanel2.add(jLabel12);
        jLabel12.setBounds(10, 200, 110, 25);

        jLabel13.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel13.setText("Pas");
        jPanel2.add(jLabel13);
        jLabel13.setBounds(240, 200, 50, 25);

        jLabel14.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel14.setText("Tipo Doc.");
        jPanel2.add(jLabel14);
        jLabel14.setBounds(250, 50, 70, 25);

        jPanel2.add(cboTipoDoc);
        cboTipoDoc.setBounds(330, 50, 140, 25);

        jLabel4.setText("Tipo Cliente");
        jPanel2.add(jLabel4);
        jLabel4.setBounds(10, 20, 110, 25);

        cboTipoCli.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboTipoCliActionPerformed(evt);
            }
        });
        jPanel2.add(cboTipoCli);
        cboTipoCli.setBounds(120, 20, 140, 25);

        jPanel2.add(cboEstCivil);
        cboEstCivil.setBounds(120, 110, 120, 25);

        jLabel15.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        jLabel15.setText("Sexo");
        jPanel2.add(jLabel15);
        jLabel15.setBounds(230, 110, 50, 25);

        cboSexo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboSexoActionPerformed(evt);
            }
        });
        jPanel2.add(cboSexo);
        cboSexo.setBounds(290, 110, 50, 25);

        cboEstado.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "S", "N" }));
        jPanel2.add(cboEstado);
        cboEstado.setBounds(330, 20, 50, 25);

        txtPais.setEditable(false);
        txtPais.setBackground(new java.awt.Color(204, 204, 204));
        jPanel2.add(txtPais);
        txtPais.setBounds(300, 200, 170, 25);

        txtDepto.setEditable(false);
        txtDepto.setBackground(new java.awt.Color(204, 204, 204));
        jPanel2.add(txtDepto);
        txtDepto.setBounds(120, 200, 120, 25);

        txtCodTit.setEditable(false);
        txtCodTit.setBackground(new java.awt.Color(204, 204, 204));
        txtCodTit.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        jPanel2.add(txtCodTit);
        txtCodTit.setBounds(410, 20, 60, 19);

        getContentPane().add(jPanel2);
        jPanel2.setBounds(20, 100, 490, 300);

        tabClientes.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        tabClientes.setModel(new javax.swing.table.DefaultTableModel(new Object[][] {

        }, new String[] { "Tipo Cliente", "Codigo Titular", "Tipo Doc.", "Nombre", "Estado Civil", "Direccion",
                "Localidad", "Telefono", "Celular", "Email", "Estado", "Sexo", "NroTrans" }) {
            boolean[] canEdit = new boolean[] { false, false, false, false, false, false, false, false, false,
                    false, false, false, false };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit[columnIndex];
            }
        });
        tabClientes.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        tabClientes.getTableHeader().setReorderingAllowed(false);
        tabClientes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tabClientesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(tabClientes);

        getContentPane().add(jScrollPane1);
        jScrollPane1.setBounds(20, 410, 490, 150);

        cmdCerrar.setText("Cerrar");
        cmdCerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cmdCerrarActionPerformed(evt);
            }
        });
        getContentPane().add(cmdCerrar);
        cmdCerrar.setBounds(450, 580, 63, 23);
        getContentPane().add(jSeparator1);
        jSeparator1.setBounds(20, 570, 490, 10);

        pack();
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void cmdCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCerrarActionPerformed
        this.st.close();
        this.setVisible(false);
        this.dispose();
    }//GEN-LAST:event_cmdCerrarActionPerformed

    private void tabClientesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabClientesMouseClicked
        seleccionarItem();
    }//GEN-LAST:event_tabClientesMouseClicked

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing

    }//GEN-LAST:event_formWindowClosing

    private void cboLocalidadMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_cboLocalidadMouseClicked
        completarUbicacion();
    }//GEN-LAST:event_cboLocalidadMouseClicked

    private void cboTipoCliActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboTipoCliActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cboTipoCliActionPerformed

    private void cmdReporteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdReporteActionPerformed
        informe();
    }//GEN-LAST:event_cmdReporteActionPerformed

    private void cmdCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdCancelarActionPerformed
        this.cmdBorrar.setEnabled(true);
        this.cmdEditar.setEnabled(true);
        this.cmdGuardar.setEnabled(false);
        this.cmdCancelar.setVisible(false);
        inicializarCampos();
        deshabilitarCampos();
    }//GEN-LAST:event_cmdCancelarActionPerformed

    private void cmdBorrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdBorrarActionPerformed
        Permisos per = new Permisos();
        Boolean elimino = per.PuedeEliminar(usuario, formulario);
        if (!elimino) {
            JOptionPane.showMessageDialog(null,
                    "El usuario " + usuario + " no tiene permiso para eliminar" + " en el formulario " + formulario,
                    "Permisos", JOptionPane.INFORMATION_MESSAGE);
        } else {
            int selectedRow = this.tabClientes.getSelectedRow();
            if (selectedRow < 0) {
                JOptionPane.showMessageDialog(null, "Debe seleccionar un registro a eliminar.",
                        "Mantenimiento de Bancos", JOptionPane.ERROR_MESSAGE);
            } else {
                if (this.txtCodTit.getText().isEmpty()) {
                    JOptionPane.showMessageDialog(null,
                            "Debe seleccionar un elemnto de la grilla. Operacin cancelada.",
                            "Mantenimiento de Clientes", JOptionPane.ERROR_MESSAGE);
                } else {
                    int showConfirmDialog = JOptionPane.showConfirmDialog(null, "Eliminacin de Registro",
                            "Desea eliminar este registro.", JOptionPane.YES_NO_OPTION);
                    if (showConfirmDialog == 1) {
                        JOptionPane.showMessageDialog(null, "Operacin cancelada.", "Mantenimiento de Clientes",
                                JOptionPane.INFORMATION_MESSAGE);
                    } else {
                        try {
                            st.beginTransaction();
                            Object valueAt = model.getValueAt(selectedRow, 12);
                            String codDpto = valueAt.toString();
                            MtDepartamentos registro = (MtDepartamentos) st.load(MtDepartamentos.class,
                                    Integer.parseInt(codDpto));
                            st.delete(registro);
                            st.getTransaction().commit();
                            cargarTabla();
                            JOptionPane.showMessageDialog(null, "Registro eliminado.", "Mantenimiento de Clientes",
                                    JOptionPane.INFORMATION_MESSAGE);
                        } catch (HibernateException | HeadlessException ex) {
                            JOptionPane.showMessageDialog(null,
                                    "Ocurri un error al eliminar el registro. " + ex.getMessage(),
                                    "Mantenimiento de Clientes", JOptionPane.ERROR_MESSAGE);
                        }
                    }
                }
            }
        }
    }//GEN-LAST:event_cmdBorrarActionPerformed

    private void cmdEditarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdEditarActionPerformed

        Permisos per = new Permisos();
        Boolean edito = per.PuedeModificar(usuario, formulario);
        if (!edito) {
            JOptionPane.showMessageDialog(null,
                    "El usuario " + usuario + " no tiene permiso para editar" + " en el formulario " + formulario,
                    "Permisos", JOptionPane.INFORMATION_MESSAGE);
        } else {
            this.setOrigen("Editar");
            this.cmdGuardar.setEnabled(true);
            this.cmdCancelar.setVisible(true);
            habilitarCampos();
        }

    }//GEN-LAST:event_cmdEditarActionPerformed

    private void cmdGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdGuardarActionPerformed
        guardar();
    }//GEN-LAST:event_cmdGuardarActionPerformed

    private void cmdNuevoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cmdNuevoActionPerformed
        Permisos per = new Permisos();
        Boolean inserto = per.PuedeInsertar(usuario, formulario);
        if (!inserto) {
            JOptionPane.showMessageDialog(null,
                    "El usuario " + usuario + " no tiene permiso para insertar" + " en el formulario " + formulario,
                    "Permisos", JOptionPane.INFORMATION_MESSAGE);
        } else {
            this.setOrigen("Nuevo");
            habilitarCampos();
            inicializarCampos();

            this.cmdBorrar.setEnabled(false);
            this.cmdEditar.setEnabled(false);
            this.cmdGuardar.setEnabled(true);
            this.cmdCancelar.setVisible(true);
        }
    }//GEN-LAST:event_cmdNuevoActionPerformed

    private void cboSexoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboSexoActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cboSexoActionPerformed

    private void txtNroDocumFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_txtNroDocumFocusLost
        if (!this.txtCodTit.getText().trim().equals("")) {
            validarCliente();
        } else {
            JOptionPane.showMessageDialog(null, "Debe ingresar el cdigo de cliente.", "Mantenimiento de Clientes",
                    JOptionPane.INFORMATION_MESSAGE);
            this.txtCodTit.grabFocus();
        }
    }//GEN-LAST:event_txtNroDocumFocusLost

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException
                | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Clientes.class.getName()).log(java.util.logging.Level.SEVERE, null,
                    ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                Clientes dialog = new Clientes(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox cboEstCivil;
    private javax.swing.JComboBox cboEstado;
    private javax.swing.JComboBox cboLocalidad;
    private javax.swing.JComboBox cboSexo;
    private javax.swing.JComboBox cboTipoCli;
    private javax.swing.JComboBox cboTipoDoc;
    private javax.swing.JButton cmdBorrar;
    private javax.swing.JButton cmdCancelar;
    private javax.swing.JButton cmdCerrar;
    private javax.swing.JButton cmdEditar;
    private javax.swing.JButton cmdGuardar;
    private javax.swing.JButton cmdNuevo;
    private javax.swing.JButton cmdReporte;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel13;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTable tabClientes;
    private javax.swing.JTextField txtCelular;
    private javax.swing.JTextField txtCodTit;
    private javax.swing.JTextField txtDepto;
    private javax.swing.JTextField txtDireccion;
    private javax.swing.JTextField txtEmail;
    private javax.swing.JTextField txtNombre;
    private javax.swing.JTextField txtNroDocum;
    private javax.swing.JTextField txtPais;
    private javax.swing.JTextField txtTelefono;
    // End of variables declaration//GEN-END:variables

    private void setUsuario(String user) {
        this.usuario = user;
    }

    public String getUsuario() {
        return this.usuario;
    }

    private void setOrigen(String orig) {
        this.origen = orig;
    }

    public String getOrigen() {
        return this.origen;
    }

    private void hibernateSession() {
        this.st = HibernateUtil.getSessionFactory().openSession();
    }

    private void arranque() {
        this.cmdCancelar.setVisible(false);
        cargarCombo();
        tableModel();
        cargarTabla();
        inicializarCampos();
        deshabilitarCampos();
    }

    public void tableModel() {
        model = (DefaultTableModel) this.tabClientes.getModel();
        model.setNumRows(0);
    }

    public void cargarTabla() {
        try {
            List<MtClientes> lista = (List<MtClientes>) st.createQuery("from MtClientes").list();
            for (MtClientes clientesList : lista) {
                model.addRow(new Object[] { clientesList.getMtTiposClientes().getNomTipoCliente(),
                        clientesList.getNroDocum(), clientesList.getMtTipoDocumentos().getTipoDocValor(),
                        clientesList.getNomTit(), clientesList.getMtEstcivil().getNomEstcivil(),
                        clientesList.getDirTitular(), clientesList.getMtCiudades().getNomCiudad(),
                        clientesList.getTelTitular(), clientesList.getCelTitular(), clientesList.getEmail(),
                        clientesList.getEsActivo(), clientesList.getMtSexos().getCodSexo(),
                        clientesList.getCodTit() });
            }
        } catch (HibernateException ex) {
            JOptionPane.showMessageDialog(null, "Ocurrio un error al cargar la grilla. " + ex.getMessage(),
                    "Mantenimiento de Clientes", JOptionPane.ERROR_MESSAGE);
        }
    }

    public void guardar() {
        Date fecha = new Date();
        if (this.txtNroDocum.getText().isEmpty()) {
            JOptionPane.showMessageDialog(null, "Ingrese un numero de documento", "Mantenimiento de Clientes",
                    JOptionPane.INFORMATION_MESSAGE);
            this.txtNroDocum.grabFocus();
        } else {
            if (this.txtNombre.getText().isEmpty()) {
                JOptionPane.showMessageDialog(null, "Ingrese el nombre del titular.", "Mantenimiento de Clientes",
                        JOptionPane.INFORMATION_MESSAGE);
                this.txtNombre.grabFocus();
            } else { // procede a la persistencia del registro.

                Object ciudad = this.cboLocalidad.getSelectedItem();
                MtCiudades nomCiudad = retornoCiudad(ciudad.toString());

                Object tipoDoc = this.cboTipoDoc.getSelectedItem();
                MtTipoDocumentos nomTipoDoc = retornoTipoDoc(tipoDoc.toString());

                Object estCivil = this.cboEstCivil.getSelectedItem().toString();
                MtEstcivil estadoCivil = retornoEstCivil(estCivil.toString());

                Object tipoCli = this.cboTipoCli.getSelectedItem().toString();
                MtTiposClientes tipoCliente = retornoTipoCli(tipoCli.toString());

                if (this.origen.equals("Nuevo")) {
                    try {
                        st.beginTransaction();
                        MtClientes registro = new MtClientes();

                        registro.setCodTit(this.txtNroDocum.getText());
                        registro.setNroDocum(this.txtNroDocum.getText());
                        registro.setNomTit(this.txtNombre.getText());
                        registro.setDirTitular(this.txtDireccion.getText());
                        registro.setTelTitular(this.txtTelefono.getText());
                        registro.setCelTitular(this.txtCelular.getText());
                        registro.setEmail(this.txtEmail.getText());
                        registro.setEsActivo(retornoEstado(this.cboEstCivil.getSelectedIndex()));
                        registro.setMtTipoDocumentos(nomTipoDoc);
                        System.out.println(
                                "Seleccionado en Tipo Doc..> " + this.cboTipoDoc.getSelectedItem().toString());
                        System.out
                                .println("Retorno en cboTipoDoc..> " + registro.getMtTipoDocumentos().getNombre());
                        registro.setMtEstcivil(estadoCivil);
                        System.out.println(
                                "Seleccionado en EstadoCivil..> " + this.cboEstCivil.getSelectedItem().toString());
                        System.out.println(
                                "Retorno en cboEstadoCivil..> " + registro.getMtEstcivil().getNomEstcivil());
                        registro.setMtSexos(retornoSexo(this.cboSexo.getSelectedItem().toString().charAt(0)));
                        registro.setMtCiudades(nomCiudad);
                        System.out.println(
                                "Seleccionado en Localidad..> " + this.cboLocalidad.getSelectedItem().toString());
                        System.out.println("Retorno en cboLocalidad..> " + registro.getMtCiudades().getNomCiudad());
                        registro.setMtTiposClientes(tipoCliente);
                        registro.setAccionMod(origen);
                        registro.setUsuarioMod(usuario);
                        registro.setFechaMod(fecha);

                        st.save(registro);
                        st.getTransaction().commit();
                        JOptionPane.showMessageDialog(null, "Cliente ingresado exitosamente.",
                                "Mantenimiento de Clientes", JOptionPane.INFORMATION_MESSAGE);
                        arranque();
                    } catch (HibernateException | HeadlessException ex) {
                        st.beginTransaction().rollback();
                        JOptionPane.showMessageDialog(null, "Error al guardar registro. " + ex.getMessage(),
                                "Mantenimiento de Clientes", JOptionPane.ERROR_MESSAGE);
                    }
                } else {
                    // procede a la persistencia del registro.
                    try {
                        st.beginTransaction();

                        MtClientes registro = (MtClientes) st.load(MtClientes.class,
                                Integer.parseInt(this.txtCodTit.getText()));

                        registro.setNroDocum(this.txtNroDocum.getText());
                        registro.setNomTit(this.txtNombre.getText());
                        registro.setDirTitular(this.txtDireccion.getText());
                        registro.setTelTitular(this.txtTelefono.getText());
                        registro.setCelTitular(this.txtCelular.getText());
                        registro.setEmail(this.txtEmail.getText());
                        registro.setEsActivo(retornoEstado(this.cboEstCivil.getSelectedIndex()));
                        registro.setMtTipoDocumentos(nomTipoDoc);
                        registro.setMtEstcivil(estadoCivil);
                        registro.setMtSexos(retornoSexo(this.cboSexo.getSelectedItem().toString().charAt(0)));
                        registro.setMtTiposClientes(tipoCliente);
                        //registro.setMtCiudades(retornoCiudad(this.cboLocalidad.getSelectedItem().toString()));  
                        registro.setMtCiudades(nomCiudad);
                        registro.setAccionMod(origen);
                        registro.setUsuarioMod(usuario);
                        registro.setFechaMod(fecha);

                        st.update(registro);
                        st.getTransaction().commit();
                        JOptionPane.showMessageDialog(null, "Registro actualizado correctamente.",
                                "Mantenimiento de Clientes", JOptionPane.INFORMATION_MESSAGE);
                        arranque();

                    } catch (HibernateException | HeadlessException ex) {
                        st.beginTransaction().rollback();
                        JOptionPane.showMessageDialog(null, "Error al guardar registro. \\n" + ex.getMessage(),
                                "Mantenimiento de Clientes", JOptionPane.INFORMATION_MESSAGE);
                    }
                }
            }
        }
        this.cmdEditar.setEnabled(true);
        this.cmdBorrar.setEnabled(true);
        deshabilitarCampos();
    }

    public void cargarCombo() {
        cargarCboTipoCli();
        cargarCboEstCivil();
        cargarCboSexo();
        cargarCboTipoDoc();
        cargarCboLocalidades();
    }

    public void cargarCboEstCivil() {
        this.cboEstCivil.removeAllItems();
        List<MtEstcivil> lista = (List<MtEstcivil>) st.createQuery("From MtEstcivil").list();
        for (MtEstcivil estList : lista) {
            this.cboEstCivil.addItem(estList.getNomEstcivil());
        }
    }

    public void cargarCboTipoCli() {
        this.cboTipoCli.removeAllItems();
        List<MtTiposClientes> lista = (List<MtTiposClientes>) st.createQuery("From MtTiposClientes").list();
        for (MtTiposClientes tipoCliList : lista) {
            this.cboTipoCli.addItem(tipoCliList.getNomTipoCliente());
        }
    }

    public void cargarCboSexo() {
        this.cboSexo.removeAllItems();
        List<MtSexos> lista = (List<MtSexos>) st.createQuery("From MtSexos order by codSexo").list();
        for (MtSexos sexoList : lista) {
            this.cboSexo.addItem(sexoList.getCodSexo());
        }
    }

    public void cargarCboTipoDoc() {
        this.cboTipoDoc.removeAllItems();
        List<MtTipoDocumentos> lista = (List<MtTipoDocumentos>) st.createQuery("From MtTipoDocumentos").list();
        for (MtTipoDocumentos tipoDocList : lista) {
            this.cboTipoDoc.addItem(tipoDocList.getTipoDocValor());
        }
    }

    public void cargarCboLocalidades() {
        this.cboLocalidad.removeAllItems();
        List<MtCiudades> lista = (List<MtCiudades>) st.createQuery("From MtCiudades").list();
        for (MtCiudades ciudadList : lista) {
            this.cboLocalidad.addItem(ciudadList.getNomCiudad());
        }
    }

    private void seleccionarItem() {
        int selectedRow = this.tabClientes.getSelectedRow();
        this.cboTipoCli.setSelectedItem(model.getValueAt(selectedRow, 0).toString());
        this.txtNroDocum.setText(model.getValueAt(selectedRow, 1).toString());
        this.cboTipoDoc.setSelectedItem(model.getValueAt(selectedRow, 2).toString());
        this.txtNombre.setText(model.getValueAt(selectedRow, 3).toString());
        this.cboEstCivil.setSelectedItem(model.getValueAt(selectedRow, 4).toString());
        this.txtDireccion.setText(model.getValueAt(selectedRow, 5).toString());
        this.cboLocalidad.setSelectedItem(model.getValueAt(selectedRow, 6).toString());
        completarUbicacion();
        this.txtTelefono.setText(model.getValueAt(selectedRow, 7).toString());
        this.txtCelular.setText(model.getValueAt(selectedRow, 8).toString());
        this.txtEmail.setText(model.getValueAt(selectedRow, 9).toString());
        this.cboEstado.setSelectedItem(model.getValueAt(selectedRow, 10).toString().charAt(0));
        this.cboSexo.setSelectedItem(model.getValueAt(selectedRow, 11).toString().charAt(0));
        this.txtCodTit.setText(model.getValueAt(selectedRow, 12).toString());
    }

    public int obtenerNroTrans() {
        int cantidad = 0;
        try {
            Query query = st.createQuery("select max(d.codTit) from MtClientes d");
            cantidad = (int) query.uniqueResult();
        } catch (HibernateException ex) {
            JOptionPane.showMessageDialog(null, "Ocurrio un error al obtener el nroTrans." + ex.getMessage(),
                    "Mantenimiento de Clientes", JOptionPane.ERROR_MESSAGE);
        } catch (NullPointerException ex) {
            cantidad = 0;
        }
        return (cantidad + 1);
    }

    private void inicializarCampos() {
        this.txtNroDocum.setText("");
        this.txtCelular.setText("");
        this.txtDireccion.setText("");
        this.txtEmail.setText("");
        this.txtNombre.setText("");
        this.txtTelefono.setText("");
        this.txtCodTit.setText("");
        this.cboSexo.setSelectedIndex(-1);
        this.cboLocalidad.setSelectedIndex(-1);
        this.cboEstCivil.setSelectedIndex(-1);
        this.cboTipoCli.setSelectedIndex(-1);
        this.cboTipoDoc.setSelectedIndex(-1);
    }

    private void deshabilitarCampos() {
        this.txtNroDocum.setEditable(false);
        this.txtCelular.setEditable(false);
        this.txtDireccion.setEditable(false);
        this.txtEmail.setEditable(false);
        this.txtNombre.setEditable(false);
        this.txtTelefono.setEditable(false);
        this.txtCodTit.setEditable(false);
        this.cboSexo.setEditable(false);
        this.cboLocalidad.setEditable(false);
        this.cboEstCivil.setEditable(false);
        this.cboTipoCli.setEditable(false);
        this.cboTipoDoc.setEditable(false);
        this.tabClientes.setEnabled(true);
    }

    private void habilitarCampos() {
        this.txtNroDocum.setEditable(true);
        this.txtCelular.setEditable(true);
        this.txtDireccion.setEditable(true);
        this.txtEmail.setEditable(true);
        this.txtNombre.setEditable(true);
        this.txtTelefono.setEditable(true);
        this.txtCodTit.setEditable(true);
        this.cboSexo.setEditable(true);
        this.cboLocalidad.setEditable(true);
        this.cboEstCivil.setEditable(true);
        this.cboTipoCli.setEditable(true);
        this.cboTipoDoc.setEditable(true);
        this.tabClientes.setEnabled(false);
    }

    public char retornoEstado(int indice) {
        if (indice == 0) {
            return 'S';
        } else {
            return 'N';
        }
    }

    public void completarUbicacion() {
        String pais = "";
        String dpto = "";
        try {
            MtCiudades ciudad = retornoCiudad(this.cboLocalidad.getSelectedItem().toString());
            dpto = ciudad.getMtDepartamentos().getNomDepartamento();
            pais = ciudad.getMtDepartamentos().getMtPaises().getNomPais();
        } catch (NullPointerException ex) {
            dpto = "";
            pais = "";
        }
        this.txtDepto.setText(dpto);
        this.txtPais.setText(pais);
    }

    public MtTiposClientes retornoTipoCli(String tipoCli) {
        MtTiposClientes retTipoCli = null;
        try {
            Query query = st.createQuery("From MtTiposClientes c Where c.nomTipoCliente = ?");
            query.setParameter(0, tipoCli);
            try {
                retTipoCli = (MtTiposClientes) query.uniqueResult();
            } catch (HibernateException e) {
                JOptionPane.showMessageDialog(null, "(retornoTipoCli) Error: " + tipoCli + e.getMessage(),
                        "Mantenimiento de Clientes", JOptionPane.INFORMATION_MESSAGE);
            }
        } catch (HeadlessException | HibernateException e) {
        }
        return retTipoCli;
    }

    public MtTipoDocumentos retornoTipoDoc(String tipo) {
        MtTipoDocumentos docRet = null;
        Query query = st.createQuery("From MtTipoDocumentos t Where t.tipoDocValor = ?");
        query.setParameter(0, tipo);
        try {
            docRet = (MtTipoDocumentos) query.uniqueResult();
            //docRet = (MtTipoDocumentos) query.list();

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Hay mas registros repetidos: " + tipo, "Mantenimiento de Clientes",
                    JOptionPane.INFORMATION_MESSAGE);
            System.out.println("Error al recuperar tipoDocumento. (" + tipo + ")  -   " + e.getMessage());
            e.printStackTrace();
        }
        return docRet;
    }

    public MtEstcivil retornoEstCivil(String codEstado) {
        MtEstcivil estadoCivilRet = null;
        try {
            Query query = st.createQuery("From MtEstcivil t Where t.nomEstcivil = ?");
            query.setParameter(0, codEstado);
            try {
                estadoCivilRet = (MtEstcivil) query.uniqueResult();
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "Hay ms resgistros repetidos: " + codEstado,
                        "Mantenimiento de Clientes", JOptionPane.INFORMATION_MESSAGE);
                System.out.println("Error al recuperar estadoCivil. " + e.getMessage());
            }
        } catch (HibernateException | HeadlessException e) {
            System.out.println("Error al recuperar estadoCivil. " + e.getMessage());
        }
        return estadoCivilRet;
    }

    public MtSexos retornoSexo(char sexo) {
        try {
            MtSexos sexoRet = (MtSexos) st.get(MtSexos.class, sexo);
            return sexoRet;
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "(retornoSexo) Error " + sexo + " - " + ex.getMessage(),
                    "Mantenimiento de Clientes", JOptionPane.INFORMATION_MESSAGE);
            System.out.println("Error al recuperar sexo. " + ex.getMessage());
        }
        return null;
    }

    public MtCiudades retornoCiudad(String nomCiudad) {
        MtCiudades retCiudad = null;
        try {
            Query query = st.createQuery("From MtCiudades c Where c.nomCiudad = ?");
            query.setParameter(0, nomCiudad);
            try {
                retCiudad = (MtCiudades) query.uniqueResult();
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(null, "Error al recuperar registros ciudad: " + nomCiudad);
                System.out.println(ex.getMessage());
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Ha ocurrido un error. ");
            System.out.println(e.getMessage());
        }
        return retCiudad;
    }

    private void validarCliente() {
        MtClientes cliente = null;
        String param = this.txtCodTit.getText();
        Query query = st.createQuery("From MtClientes c Where c.cod_tit = ?");
        query.setParameter(0, param);

        try {
            cliente = (MtClientes) query.uniqueResult();

            if (cliente != null) {
                this.txtCodTit.grabFocus();
                JOptionPane.showMessageDialog(null, "El cdigo ingresado ya existe.", "Mantenimiento de Clientes",
                        JOptionPane.INFORMATION_MESSAGE);
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null,
                    "Error al validar cdigo del cliente" + "\n" + e.getMessage() + "\n" + e.getCause(),
                    "Mantenimiento de Clientes", JOptionPane.INFORMATION_MESSAGE);
        }
    }

    public void informe() {
        try {
            Connection conexion;
            conexion = DriverManager.getConnection("jdbc:postgresql://localhost:5432/karu", "karu", "karu");

            JasperReport elReporte = (JasperReport) JRLoader
                    .loadObject(ClassLoader.getSystemResource("com/informes/Clientes_Lista.jasper"));
            JasperPrint imprimir = JasperFillManager.fillReport(elReporte, null, conexion);
            JasperViewer visor = new JasperViewer(imprimir, false);
            visor.setTitle("Listado de Clientes");
            visor.setVisible(true);
            conexion.close();
        } catch (SQLException | JRException e) {
            String mensajeEx = e.getMessage();
            JOptionPane.showMessageDialog(null, "Error cargando reporte. " + mensajeEx);
        }
    }
}