/*
 * 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 Calculos_automaticos;

import arql2020.ARQL2020;
import static arql2020.ARQL2020.WHERE;
import clases.InteraccionesBD;
import clases.conexion;
import java.awt.BorderLayout;
import java.awt.Color;
import java.beans.PropertyVetoException;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTree;
import javax.swing.table.DefaultTableModel;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;

/**
 *
 * @author chuen
 */
public class C_Sistema_de_produccion extends javax.swing.JInternalFrame {

    /**
     * Creates new form C_Sistema_de_produccion
     */
    public C_Sistema_de_produccion() {
        initComponents();
                try {
            this.setMaximum(true);
        } catch (PropertyVetoException ex) {
            Logger.getLogger(B_Composicion_puntasfilossup.class.getName()).log(Level.SEVERE, null, ex);
        }
    
    }

    

    /**
     * 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() {

        botones = new javax.swing.ButtonGroup();
        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel2 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jpanel = new javax.swing.JPanel();
        jpanel1 = new javax.swing.JPanel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        cbx_mp = new javax.swing.JComboBox<>();
        jLabel2 = new javax.swing.JLabel();
        cbx_modulos = new javax.swing.JComboBox<>();
        jLabel3 = new javax.swing.JLabel();
        cbx_subgrusponucleos = new javax.swing.JComboBox<>();
        jScrollPane2 = new javax.swing.JScrollPane();
        tbl2 = new javax.swing.JTable();
        jScrollPane4 = new javax.swing.JScrollPane();
        txtSistemadeproduccion = new javax.swing.JTextArea();
        jScrollPane3 = new javax.swing.JScrollPane();
        tbl1 = new javax.swing.JTable();
        jLabel4 = new javax.swing.JLabel();
        btn_calcular = new javax.swing.JButton();
        jLabel14 = new javax.swing.JLabel();
        txt_muestra = new javax.swing.JTextField();
        jLabel15 = new javax.swing.JLabel();
        txt_mp_selec = new javax.swing.JTextField();
        jLabel16 = new javax.swing.JLabel();
        txt_sentencia = new javax.swing.JTextField();
        btn_info = new javax.swing.JButton();
        btn_arbol = new javax.swing.JButton();
        btn_copiar = new javax.swing.JButton();
        jLabel17 = new javax.swing.JLabel();
        txt_modulo = new javax.swing.JTextField();
        jLabel18 = new javax.swing.JLabel();
        txt_subgruponu = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jScrollPane5 = new javax.swing.JScrollPane();
        tbl3 = new javax.swing.JTable();
        jScrollPane6 = new javax.swing.JScrollPane();
        txt_expandir = new javax.swing.JTextArea();
        jLabel7 = new javax.swing.JLabel();
        btn_copiar1 = new javax.swing.JButton();
        copiar_modulo_nu = new javax.swing.JButton();

        setClosable(true);
        setMaximizable(true);
        setResizable(true);
        setTitle("Sistema de producción");
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameOpened(evt);
            }
        });

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 14))); // NOI18N

        jpanel.setBackground(new java.awt.Color(204, 204, 204));
        jpanel.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jpanel.setLayout(new java.awt.BorderLayout());

        jpanel1.setBackground(new java.awt.Color(204, 204, 204));
        jpanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jpanel1.setLayout(new java.awt.BorderLayout());

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel5.setText("Gráficos por fila (Según tamaño)");

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel6.setText("Gráficos por columna (según DT, utiles o nucleos)");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jpanel, javax.swing.GroupLayout.PREFERRED_SIZE, 494, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel6)
                    .addComponent(jpanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 494, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(13, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jpanel, javax.swing.GroupLayout.DEFAULT_SIZE, 280, Short.MAX_VALUE)
                    .addComponent(jpanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addGap(23, 23, 23))
        );

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Materia prima: ");

        cbx_mp.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cbx_mp.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cbx_mpItemStateChanged(evt);
            }
        });

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("Módulo");

        cbx_modulos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cbx_modulos.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "A", "B", "C", "D", "E", "F", "G", "H" }));

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel3.setText("Subgrupo tipologico de núcleo");

        cbx_subgrusponucleos.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        cbx_subgrusponucleos.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Subgrupos tipológicos de Núcleos", "1-1.Núcleo de lascas: Poliédrico", "1-2.Núcleo de lascas: Discoidal", "1-3.Núcleo de lascas: Bifacial", "1-4.Núcleo de lascas: Prismático atípico de lascas", "1-9.Núcleo de lascas: Otro no diferenciado de lascas", "2-1.Núcleo de hojas: Prismático de hojas de extracciones unidireccionales", "2-2.Núcleo de hojas: Prismático de hojas de extracciones bidireccionales", "2-3.Núcleo de hojas: Piramidal", "2-9.Núcleo de hojas: Otro de hojas no diferenciados", "3.Núcleo de extacciones combinadas", "4.Nucleiforme", "5.Globuloso o agotado", "6.Núcleo de lascados aislados", "7.Núcleo bipolar", "9.Fragmento no diferenciado de núcleo", "CN" }));

        tbl2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        tbl2.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"1", "", "", null, ""},
                {"2", "", "", null, ""},
                {"3", "", "", null, ""},
                {"4", "", "", null, ""}
            },
            new String [] {
                "TAMAÑO", "FORMAS BASE -  UTILES", "ÚLTIMAS CICATRICES EN NUCLEOS", "DT(CT)", "Total"
            }
        ));
        tbl2.setGridColor(new java.awt.Color(255, 102, 102));
        tbl2.setRowHeight(30);
        tbl2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbl2MouseClicked(evt);
            }
        });
        tbl2.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tbl2KeyPressed(evt);
            }
        });
        jScrollPane2.setViewportView(tbl2);
        if (tbl2.getColumnModel().getColumnCount() > 0) {
            tbl2.getColumnModel().getColumn(4).setHeaderValue("Total");
        }

        txtSistemadeproduccion.setEditable(false);
        txtSistemadeproduccion.setColumns(20);
        txtSistemadeproduccion.setFont(new java.awt.Font("Monospaced", 0, 14)); // NOI18N
        txtSistemadeproduccion.setLineWrap(true);
        txtSistemadeproduccion.setRows(5);
        txtSistemadeproduccion.setWrapStyleWord(true);
        txtSistemadeproduccion.setAutoscrolls(false);
        jScrollPane4.setViewportView(txtSistemadeproduccion);

        tbl1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        tbl1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        tbl1.setGridColor(new java.awt.Color(255, 102, 102));
        tbl1.setRowHeight(30);
        tbl1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbl1MouseClicked(evt);
            }
        });
        tbl1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tbl1KeyPressed(evt);
            }
        });
        jScrollPane3.setViewportView(tbl1);

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel4.setText("Seleccione la combinación correspondiente");

        btn_calcular.setBackground(new java.awt.Color(204, 255, 0));
        btn_calcular.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/lentes.png"))); // NOI18N
        btn_calcular.setToolTipText("Realizar análisis");
        btn_calcular.addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentHidden(java.awt.event.ComponentEvent evt) {
                btn_calcularComponentHidden(evt);
            }
        });
        btn_calcular.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_calcularActionPerformed(evt);
            }
        });

        jLabel14.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel14.setText("Cálculo realizado sobre muestra:");

        txt_muestra.setEditable(false);
        txt_muestra.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jLabel15.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel15.setText("Materia prima:");

        txt_mp_selec.setEditable(false);
        txt_mp_selec.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jLabel16.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel16.setText("Sentencia:");

        txt_sentencia.setEditable(false);
        txt_sentencia.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        btn_info.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/info.png"))); // NOI18N
        btn_info.setToolTipText("Información sobre el análisis");
        btn_info.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_infoActionPerformed(evt);
            }
        });

        btn_arbol.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/arbol.png"))); // NOI18N
        btn_arbol.setToolTipText("Arbol: CLASES ARTEFACTUALES PRESENTES EN LA MP SELECCIONADA");
        btn_arbol.setEnabled(false);
        btn_arbol.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_arbolActionPerformed(evt);
            }
        });

        btn_copiar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/copiar.png"))); // NOI18N
        btn_copiar.setToolTipText("Copiar valores en el portapapeles");
        btn_copiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_copiarActionPerformed(evt);
            }
        });

        jLabel17.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel17.setText("Módulo:");

        txt_modulo.setEditable(false);
        txt_modulo.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jLabel18.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel18.setText("Subgrupo tipológico de núcleo:");

        txt_subgruponu.setEditable(false);
        txt_subgruponu.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButton1.setText("MP PRESENTES EN LA MUESTRA");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        tbl3.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        tbl3.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {"1", "", "", null},
                {"2", "", "", null},
                {"3", "", "", null},
                {"4", "", "", null}
            },
            new String [] {
                "TAMAÑO", " UTILES (ID GENERAL)", "ÚLTIMAS (CICATRICES EN NUCLEOS ID NUCLEOS)", "DT(CT)( ID DT CON TALON)"
            }
        ));
        tbl3.setGridColor(new java.awt.Color(255, 102, 102));
        tbl3.setRowHeight(30);
        tbl3.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tbl3MouseClicked(evt);
            }
        });
        tbl3.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tbl3KeyPressed(evt);
            }
        });
        jScrollPane5.setViewportView(tbl3);

        txt_expandir.setEditable(false);
        txt_expandir.setColumns(20);
        txt_expandir.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txt_expandir.setLineWrap(true);
        txt_expandir.setRows(5);
        txt_expandir.setWrapStyleWord(true);
        jScrollPane6.setViewportView(txt_expandir);

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel7.setText("Codigos de piezas contabilizadas en tabla 2: según PROCEDENCIA, MP, MODULO Y SUBGRUPO TIPOLÓGICO DE NU. SELECCIONADOS");

        btn_copiar1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/copiar.png"))); // NOI18N
        btn_copiar1.setToolTipText("Copiar valores en el portapapeles");
        btn_copiar1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_copiar1ActionPerformed(evt);
            }
        });

        copiar_modulo_nu.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/copiar.png"))); // NOI18N
        copiar_modulo_nu.setToolTipText("Copiar valores en el portapapeles");
        copiar_modulo_nu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                copiar_modulo_nuActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGap(22, 22, 22)
                                .addComponent(jLabel2)
                                .addGap(18, 18, 18)
                                .addComponent(cbx_modulos, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(39, 39, 39)
                                .addComponent(jLabel3)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cbx_subgrusponucleos, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(btn_calcular, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel14)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(txt_muestra)
                                .addGap(18, 18, 18)
                                .addComponent(jLabel16)
                                .addGap(18, 18, 18)
                                .addComponent(txt_sentencia, javax.swing.GroupLayout.PREFERRED_SIZE, 197, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGap(62, 62, 62)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jLabel15)
                                    .addComponent(jLabel17)
                                    .addComponent(jLabel18))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(txt_subgruponu)
                                    .addComponent(txt_modulo)
                                    .addComponent(txt_mp_selec))))
                        .addGap(18, 18, 18)
                        .addComponent(btn_info, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btn_arbol, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btn_copiar, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(35, 35, 35))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel4)
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane6, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane5, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jScrollPane3, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGap(16, 16, 16)
                                .addComponent(jScrollPane2)
                                .addGap(18, 18, 18)
                                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 315, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(cbx_mp, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(jButton1)
                                .addGap(59, 59, 59))
                            .addGroup(jPanel2Layout.createSequentialGroup()
                                .addGap(0, 0, Short.MAX_VALUE)
                                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(copiar_modulo_nu, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(btn_copiar1, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE))))
                        .addGap(40, 40, 40))))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(26, 26, 26)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(cbx_mp, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton1))
                .addGap(10, 10, 10)
                .addComponent(copiar_modulo_nu, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 241, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(21, 21, 21)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(cbx_modulos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(cbx_subgrusponucleos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(55, 55, 55)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(btn_calcular, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btn_arbol, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(btn_copiar, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(btn_info, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel14)
                        .addComponent(txt_sentencia, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel16)
                        .addComponent(txt_muestra, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txt_mp_selec, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel15))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txt_modulo, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel17))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txt_subgruponu, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel18))
                .addGap(62, 62, 62)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 188, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 85, Short.MAX_VALUE)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(27, 27, 27)
                .addComponent(jLabel7)
                .addGap(4, 4, 4)
                .addComponent(btn_copiar1, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane5, javax.swing.GroupLayout.PREFERRED_SIZE, 156, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jScrollPane6, javax.swing.GroupLayout.PREFERRED_SIZE, 121, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(81, 81, 81))
        );

        jScrollPane1.setViewportView(jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jScrollPane1)
                .addGap(0, 0, 0))
        );

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

    private void tbl2KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbl2KeyPressed
        
        


        
    }//GEN-LAST:event_tbl2KeyPressed

    private void tbl2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl2MouseClicked
        int filaselec = tbl2.getSelectedRow();
        int filas = tbl2.getRowCount()-1;
        
        if(filaselec<filas){
        Graficos graf = new Graficos();
        graf.generargraficofila2(tbl2, jpanel, tbl2.getValueAt(filaselec,0).toString(), "Útiles, nu y DT enteros y CT");
            
        }
        
        int col=tbl2.getColumnCount()-1;
        int columnaselec = tbl2.getSelectedColumn();
        if((columnaselec>0)&&(columnaselec<col)){
            Graficos graf = new Graficos();
            graf.generargraficocolumna(tbl2, jpanel1, tbl2.getColumnName(columnaselec), "Tamaños");
            
        }

     
    }//GEN-LAST:event_tbl2MouseClicked

    private void tbl1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl1MouseClicked
        // TODO add your handling code here:
    }//GEN-LAST:event_tbl1MouseClicked

    private void tbl1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbl1KeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_tbl1KeyPressed

    private void btn_calcularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_calcularActionPerformed
if(WHERE.equals("")){
    JOptionPane.showMessageDialog(null, "Seleccione previamente una muestra");
}else{
        if(cbx_mp.getSelectedIndex()==0){
            JOptionPane.showMessageDialog(null, "Seleccione previamente una materia prima");
        }else{
            if((cbx_modulos.getSelectedIndex()==0)||(cbx_subgrusponucleos.getSelectedIndex()==0)){
            JOptionPane.showMessageDialog(null, "Seleccione previamente un módulo y un subgrupo tipológico de núcleo");
                
            }else{
             btn_arbol.setEnabled(true);
             jpanel.removeAll();
            jpanel1.removeAll();   
            tbl2.setModel(new javax.swing.table.DefaultTableModel(
    new Object [][] {
        {"1", "", "", null, ""},
        {"2", "", "", null, ""},
        {"3", "", "", null, ""},
        {"4", "", "", null, ""}
    },
    new String [] {
        "TAMAÑO", "FORMAS BASE -  UTILES", "ÚLTIMAS CICATRICES EN NUCLEOS", "DT(CT)", "Total"
    }
));
            
            txtSistemadeproduccion.setText("");
            txt_muestra.setText(ARQL2020.etiqueta_muestra);
            txt_sentencia.setText(ARQL2020.WHERE);
            txt_mp_selec.setText(cbx_mp.getSelectedItem().toString());
            txt_modulo.setText(cbx_modulos.getSelectedItem().toString());
            txt_subgruponu.setText(cbx_subgrusponucleos.getSelectedItem().toString());
//            cargartabla2();
            cargarDT("1", 3, 0, WHERE, txt_mp_selec.getText(), txt_modulo.getText());
            cargarDT("2", 3, 1, WHERE, txt_mp_selec.getText(), txt_modulo.getText());
            cargarDT("3", 3, 2, WHERE, txt_mp_selec.getText(), txt_modulo.getText());
            cargarDT("4", 3, 3, WHERE, txt_mp_selec.getText(), txt_modulo.getText());
            
            contarNU_SUBGRUPO_MODULO_TAMAÑO(0,2,txt_subgruponu.getText(), txt_modulo.getText(), "1", WHERE, txt_mp_selec.getText());
            contarNU_SUBGRUPO_MODULO_TAMAÑO(1,2,txt_subgruponu.getText(), txt_modulo.getText(), "2", WHERE, txt_mp_selec.getText());
            contarNU_SUBGRUPO_MODULO_TAMAÑO(2,2,txt_subgruponu.getText(), txt_modulo.getText(), "3", WHERE, txt_mp_selec.getText());
            contarNU_SUBGRUPO_MODULO_TAMAÑO(3,2,txt_subgruponu.getText(), txt_modulo.getText(), "4", WHERE, txt_mp_selec.getText());

            contarutiles(0,1,"1", txt_sentencia.getText(), txt_mp_selec.getText(), txt_modulo.getText());
            contarutiles(1,1,"2", txt_sentencia.getText(), txt_mp_selec.getText(), txt_modulo.getText());
            contarutiles(2,1,"3", txt_sentencia.getText(), txt_mp_selec.getText(), txt_modulo.getText());
            contarutiles(3,1,"4", txt_sentencia.getText(), txt_mp_selec.getText(), txt_modulo.getText());
            
            tbl2.setValueAt("0", 0, 4);
            tbl2.setValueAt("0", 1, 4);
            tbl2.setValueAt("0", 2, 4);
            tbl2.setValueAt("0", 3, 4);
            
            DefaultTableModel dtm = (DefaultTableModel) tbl2.getModel();
            CalculosBD calc = new CalculosBD();
            calc.sumartotalesfila(dtm);
            calc.sumartotalescolumna(dtm);
            calc.porcentajesfilainferior(dtm);
            
            boolean correspondencia= false;
                for (int i = 0; i < tbl2.getRowCount()-1; i++) {
                    int a = Integer.parseInt(tbl2.getValueAt(i, 1).toString());
                    int b = Integer.parseInt(tbl2.getValueAt(i, 2).toString());
                    int c = Integer.parseInt(tbl2.getValueAt(i, 3).toString());
                    if((a>0)&&(b>0)&&(c>0)){
                        correspondencia=true;
                    }                    
                    
                }
                if(correspondencia==true){
                    txtSistemadeproduccion.setText("Sistema de producción local.");
                }
                if(correspondencia==false){
                    txtSistemadeproduccion.setText("");
                }

        }
        }
        }
    }//GEN-LAST:event_btn_calcularActionPerformed
private void contarutiles(int fila, int col, String tamaño, String where, String MP, String modulo){
CalculosBD calc=new CalculosBD();
String ids=calc.obteneridutiles(txt_sentencia.getText(), txt_mp_selec.getText());

    int numutiles=0;
ResultSet rs = null; 
     String consulta = "SELECT COUNT (*)  FROM FORMATIZADOS f  \n" +
where + " AND (f.MP='"+MP+"')  AND (f.TAMAÑO='"+tamaño+"')  AND (f.MODULO_LONG_ANCHO='"+modulo+"') "+ ids;
        
     try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);

            if(rs.next()){
                numutiles=rs.getInt("1");
            }       
        tbl2.setValueAt(numutiles, fila, col);
        c.closeconnection();
        
        
        } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
consulta = "SELECT f.ID_FORMATIZADOS FROM FORMATIZADOS f \n" +
where + " AND (f.MP='"+MP+"')  AND (f.TAMAÑO='"+tamaño+"') AND (f.MODULO_LONG_ANCHO='"+modulo+"')" + ids;
String idutiles= "";        
     try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);

            while(rs.next()){
                idutiles = idutiles + "Gen:"+rs.getInt("ID_FORMATIZADOS")+"/ ";
            }       
        
        c.closeconnection();
        
        tbl3.setValueAt(idutiles, fila, col);
        } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
     
     
}
 private void contarNU_SUBGRUPO_MODULO_TAMAÑO(int fila, int col, String subgrupo, String modulo, String tamaño, String where, String MP){
int nummods=0;
ResultSet rs = null; 
     String consulta = "SELECT COUNT (*)  FROM NUCLEOS n\n" +
"INNER JOIN\n" +
"FORMATIZADOS f\n" +
"ON f.ID_FORMATIZADOS = n.ID_FORMATIZADOS " +where + " AND (f.MP='"+MP+"') AND (n.SUBGRUPO='"+subgrupo+"') AND (n.LSMAY_MODULO='"+modulo+"') AND (n.LSMAY_TAMAÑO='"+tamaño+"')  ";
        
     try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);

            if(rs.next()){
                nummods=rs.getInt("1");
            }       
        
        c.closeconnection();
        
        
        } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
consulta = "SELECT COUNT (*)  FROM NUCLEOS n\n" +
"INNER JOIN\n" +
"FORMATIZADOS f\n" +
"ON f.ID_FORMATIZADOS = n.ID_FORMATIZADOS " +where + " AND (f.MP='"+MP+"') AND (n.SUBGRUPO='"+subgrupo+"') AND (n.LSMEN_MODULO='"+modulo+"') AND (n.LSMEN_TAMAÑO='"+tamaño+"')  ";
        
     try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);

            if(rs.next()){
                nummods=nummods+rs.getInt("1");
            }       
        
        c.closeconnection();
        
             tbl2.setValueAt(nummods, fila, col);
        } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
     
consulta = "SELECT n.ID_NUCLEOS, f.ID_FORMATIZADOS  FROM NUCLEOS n\n" +
"INNER JOIN\n" +
"FORMATIZADOS f\n" +
"ON f.ID_FORMATIZADOS = n.ID_FORMATIZADOS " +where + " AND (f.MP='"+MP+"') AND (n.SUBGRUPO='"+subgrupo+"') AND ((n.LSMEN_MODULO='"+modulo+"' AND n.LSMEN_TAMAÑO='"+tamaño+"') OR (n.LSMAY_MODULO='"+modulo+"' AND n.LSMAY_TAMAÑO='"+tamaño+"'))  ";
String codnu="";        
     try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);

            while(rs.next()){
                codnu= codnu+"GEN:"+rs.getInt("ID_FORMATIZADOS")+"-Nu:"+rs.getInt("ID_NUCLEOS")+"// ";
            }       
        
        c.closeconnection();
        
             tbl3.setValueAt(codnu, fila, col);
        } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
     
    
     
     
     
     
   
    
}   
    
    
    
    
    private void cargarDT(String Tamaño, int col, int fila, String where, String MP, String MODULO){
       ArrayList<String> subgrupo = new ArrayList<>();
     ResultSet rs = null; 
     String consulta = "SELECT COUNT (f.TAMAÑO)  FROM DT_CONTALON2 f \n" +where + " AND (f.MP='"+MP+"') AND (f.MODULO_LONG_ANCHO='"+MODULO+"') AND (f.TAMAÑO='"+Tamaño+"') ";
         try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);

            if(rs.next()){
                tbl2.setValueAt(rs.getInt("1"), fila, col);
            }       
        
        c.closeconnection();
        
        
        } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
     
     consulta = "SELECT ID_DT_CONTALON  FROM DT_CONTALON2 f \n" +where + " AND (f.MP='"+MP+"') AND (f.MODULO_LONG_ANCHO='"+MODULO+"') AND (f.TAMAÑO='"+Tamaño+"') ";
         try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);
             String id="";
           while(rs.next()){
                id=id + "CT:"+rs.getInt("ID_DT_CONTALON") + "/";
                
            }       
        tbl3.setValueAt(id, fila, col);
        c.closeconnection();
        
        
        } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
}
    private void btn_infoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_infoActionPerformed
        info_frame info = new info_frame();
        info.setVisible(true);
        info.info_procedencia.setText("MUESTRA---->" + txt_muestra.getText() +"\n SENTENCIA---->" +txt_sentencia.getText() );
        info.info_mp.setText(txt_mp_selec.getText());
        info.info_analisis.setText("SISTEMA DE PRODUCCIÓN\n" +
"\n" +
"TABLA 1. MODULOS LONG/ANCHO PRESENTES EN LOS LASCADOS DE MAYOR TAMAÑO Y LOS DE MENOR TAMAÑO DE TODOS LOS NÚCLEOS DE LA MUESTRA. SE CONTABILIZAN TODAS LAS PLATAFORMAS DE NÚCLEOS INGRESADAS.\n" +
"\n" +
"TABLA 2. EN BASE A LA MATERIA PRIMA Y EL MODULO LONG/ANCHO SELECCIONADOS, SE CONTABILIZA:\n" +
"---A: TAMAÑOS DE FORMAS BASE DE UTILES (todos los grupos artefactuales, a excepción de los núcleos) \n" +
"---B:Tamaños en cicatrices de lascado de núcleos (de mayor y de menor tamaño, contabilizando todas las plataformas ingresadas)\n" +
"---C:tamaños de desechos de talla enteros y fracturados con talon.\n" +
"\n" +
"Si existe una correlación entre todos o alguno de los tamaños de formas base de útiles, últimas cicatrices en núcleos y desechos de talla enteros y fracturados con talón, se determina que se trata de un SISTEMA DE PRODUCCIÓN LOCAL. El número mínimo para dicha correlación es de 1.");
           
    }//GEN-LAST:event_btn_infoActionPerformed

    private void btn_arbolActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_arbolActionPerformed
Arbol ar = new Arbol();
ar.setVisible(true);
CalculosBD calc = new CalculosBD();
arbolUTILESYNUCLEOS(txt_sentencia.getText(), txt_mp_selec.getText(),ar.arbol_analisis_FORM, txt_modulo.getText());
        

ar.txt_mp.setText(txt_mp_selec.getText());
ar.txt_nota.setText("El árbol se conforma con las piezas contabilizadas en la tabla 2.");

    }//GEN-LAST:event_btn_arbolActionPerformed
private void arbolUTILESYNUCLEOS(String where, String MP, JTree tree, String modulo){
    ResultSet rs = null; 
    
//////////////////////////////////SELECCIONA ID PARA UTILES    

CalculosBD calc=new CalculosBD();
String ids= calc.obteneridutiles(txt_sentencia.getText(), txt_mp_selec.getText());
ArrayList <String[]> utiles = new ArrayList<>();
         try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta("SELECT DISTINCT(f.ID_FORMATIZADOS), f.PIEZA, f.TAMAÑO FROM FORMATIZADOS f "+
                      where + " AND (f.MP='"+MP+"')"+  ids + " AND (f.MODULO_LONG_ANCHO='"+modulo+"')");
         
             
               while(rs.next()){
               String [] utiles_aux = new String[3];
               utiles_aux[0]=String.valueOf(rs.getInt("ID_FORMATIZADOS"));
               utiles_aux[1]=(rs.getString("PIEZA"));
               utiles_aux[2]=(rs.getString("TAMAÑO"));
                
               utiles.add(utiles_aux);
               
           }       
        
        c.closeconnection();
 } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
         
         
//////////////////////////////////SELECCIONA ID PARA SEGMENTAL ESTANDAR          
ArrayList <int[]> estandar = new ArrayList<>();

        try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta("SELECT ID_ESTANDAR, ID_FORMATIZADOS FROM SEGMENTAL_ESTANDAR2");

            while(rs.next()){
                int []estandar_aux = new int [2];
               estandar_aux[0]= rs.getInt("ID_ESTANDAR");
               estandar_aux[1]= rs.getInt("ID_FORMATIZADOS");
               estandar.add(estandar_aux);
           }       
        
        c.closeconnection();
 } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
        
//////////////////////////////SELECCIONA ID PARA PUNTAS 

ArrayList <int[]> puntas = new ArrayList<>();

try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta("SELECT ID_PUNTAS, ID_FORMATIZADOS FROM PUNTAS_DE_PROYECTIL2");

            while(rs.next()){
                int [] puntas_aux = new int [2];
               puntas_aux[0]= rs.getInt("ID_PUNTAS");
               puntas_aux[1]= rs.getInt("ID_FORMATIZADOS");
               puntas.add(puntas_aux);
           }       
        
        c.closeconnection();
 } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
//////////////////////////////SELECCIONA NUCLEOS

ArrayList <String[]> nucleos = new ArrayList<>();

try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta("SELECT n.ID_NUCLEOS, n.ID_FORMATIZADOS, n.N_PLAT FROM NUCLEOS n"
                     + " INNER JOIN "
                     + " FORMATIZADOS f " 
                     +" ON f.ID_FORMATIZADOS = n.ID_FORMATIZADOS " + where + " AND (f.MP='"+txt_mp_selec.getText()+"') AND (n.SUBGRUPO='"+txt_subgruponu.getText()+"') AND (n.LSMAY_MODULO='"+txt_modulo.getText()+"' OR n.LSMEN_MODULO='"+txt_modulo.getText()+"') ");
            while(rs.next()){
               String [] nu = new String[3];
               nu[0]= String.valueOf(rs.getInt("ID_NUCLEOS"));
               nu[1]= String.valueOf(rs.getInt("ID_FORMATIZADOS"));
               nu[2]= rs.getString("N_PLAT");
               nucleos.add(nu);
           }       
        
            
            
        c.closeconnection();
 } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }




/////////////ARMA EL ARBOL
DefaultTreeModel model = (DefaultTreeModel) tree.getModel();        
DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();


DefaultMutableTreeNode hoja_utiles = new DefaultMutableTreeNode("Utiles (FORM+PNRC+FNRC)");
DefaultMutableTreeNode hoja_tamaño1 = new DefaultMutableTreeNode("Tamaño: 1");
DefaultMutableTreeNode hoja_tamaño2 = new DefaultMutableTreeNode("Tamaño: 2");
DefaultMutableTreeNode hoja_tamaño3 = new DefaultMutableTreeNode("Tamaño: 3");
DefaultMutableTreeNode hoja_tamaño4 = new DefaultMutableTreeNode("Tamaño: 4");
DefaultMutableTreeNode hoja_nucleos = new DefaultMutableTreeNode("Nucleo:"+txt_subgruponu.getText()+"Modulo:"+txt_modulo.getText());
DefaultMutableTreeNode pieza = new DefaultMutableTreeNode(); 
DefaultMutableTreeNode piezanu = new DefaultMutableTreeNode(); 
MutableTreeNode hoja;
MutableTreeNode hojanu;

    
        
        for (int j = 0; j < tbl2.getRowCount()-1; j++) {
             
             
            for (int i = 0; i < utiles.size(); i++) {
            String [] IDutiles = new String[3];
            IDutiles = utiles.get(i);
            int IDpieza = Integer.parseInt(IDutiles[0]);
            
            String tamaño = IDutiles[2];
           
            
            if(tamaño.equals(tbl2.getValueAt(j, 0).toString())){
                        
            
                pieza = new DefaultMutableTreeNode(IDpieza);
                hoja = new DefaultMutableTreeNode("Gen-"+IDutiles[0]+"/"+IDutiles[1]);
                pieza.add(hoja);
                
                for (int k = 0; k < estandar.size(); k++) {
                    int [] IDestandar = new int[2];
                     IDestandar = estandar.get(k);
                    if(IDpieza==IDestandar[1]){
                    hoja = new DefaultMutableTreeNode("Seg"+"-"+IDestandar[0]+"/Pieza-"+IDestandar[1]);
                    pieza.add(hoja);
                    
                    }
                      }
                for (int m = 0; m < puntas.size(); m++) {
                    int [] IDpuntas = new int[2];
                     IDpuntas = puntas.get(m);
                    
                     if(IDpieza==IDpuntas[1]){
                    hoja = new DefaultMutableTreeNode("PP"+"-"+IDpuntas[0]+"/Pieza-"+IDpuntas[1]);
                    pieza.add(hoja);
                    }
                      }
             
                switch(tamaño){
                    case "1": hoja_tamaño1.add(pieza);
                    break;
                    case "2": hoja_tamaño2.add(pieza);
                    break;
                    case "3": hoja_tamaño3.add(pieza);
                    break;
                    case "4": hoja_tamaño4.add(pieza);
                    break;
                }
              
                
                
    }
       
         
    }
                  
      
                }
                hoja_utiles.add(hoja_tamaño1);
                hoja_utiles.add(hoja_tamaño2);
                hoja_utiles.add(hoja_tamaño3);
                hoja_utiles.add(hoja_tamaño4);

                
                
/////////////////////////////////////ARBOL NUCLEOS                
 ArrayList <String[]> idformnu = new ArrayList<>();
         try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta("SELECT DISTINCT(f.ID_FORMATIZADOS), f.PIEZA FROM FORMATIZADOS f "
                     + " INNER JOIN "
                     + " NUCLEOS n " 
                     +" ON f.ID_FORMATIZADOS = n.ID_FORMATIZADOS " 
                     + where + " AND (f.MP='"+MP+"') AND (n.SUBGRUPO='"+txt_subgruponu.getText()+"') AND (n.LSMAY_MODULO='"+txt_modulo.getText()+"' OR n.LSMEN_MODULO='"+txt_modulo.getText()+"') ");
         
             
               while(rs.next()){
               String [] aux = new String[2];
               aux[0]=String.valueOf(rs.getInt("ID_FORMATIZADOS"));
               aux[1]=rs.getString("PIEZA");
               idformnu.add(aux);
           }       
        
        c.closeconnection();
 } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
         
         
                piezanu = new DefaultMutableTreeNode("Plataformas");
                
                for (int i = 0; i < idformnu.size(); i++) {
                
                    
            
             String [] auxids = idformnu.get(i);
             String IDpieza = auxids[0];
             int IDpiezaint = Integer.parseInt(IDpieza);
           
            
                           
            
                piezanu = new DefaultMutableTreeNode(IDpieza);
                hojanu = new DefaultMutableTreeNode("Gen-"+auxids[0]+"/"+auxids[1]);
                piezanu.add(hojanu);
                
                for (int k = 0; k < estandar.size(); k++) {
                    int [] IDestandar = new int[2];
                     IDestandar = estandar.get(k);
                    if(IDpiezaint==IDestandar[1]){
                    hojanu = new DefaultMutableTreeNode("Seg"+"-"+IDestandar[0]+"/Pieza-"+IDestandar[1]);
                    piezanu.add(hojanu);
                    
                    }
                      }
                for (int m = 0; m < puntas.size(); m++) {
                    int [] IDpuntas = new int[2];
                     IDpuntas = puntas.get(m);
                    
                     if(IDpiezaint==IDpuntas[1]){
                    hojanu = new DefaultMutableTreeNode("PP"+"-"+IDpuntas[0]+"/Pieza-"+IDpuntas[1]);
                    piezanu.add(hojanu);
                    }
                      }
                    

                for (int h = 0; h < nucleos.size(); h++) {
                    String [] n = nucleos.get(h);
                    if(IDpiezaint==Integer.parseInt(n[1])){
                    hojanu = new DefaultMutableTreeNode("Nu"+"-"+n[0]+"/Pieza-"+n[1]+"/Plat-"+n[2]);
                    piezanu.add(hojanu);
                    }
                    
                      }
               
                hoja_nucleos.add(piezanu);
                }
                
                
                
                root.add(hoja_utiles);
                root.add(hoja_nucleos);
                root.setUserObject(txt_muestra.getText()+"/Modulo:"+txt_modulo.getText()+"/MP:"+txt_mp_selec.getText());
                tree.setModel(model);
                model.reload();         
         
    
}
    private void btn_copiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_copiarActionPerformed

        Copiartabla copy = new Copiartabla();
        copy.copiartabla(tbl2, txt_muestra.getText(), WHERE, "Sistema de producción: correspondencias de tamaño entre útiles, cicatrices de núcleos y DT CT", "Materia prima: "+txt_mp_selec.getText());
    }//GEN-LAST:event_btn_copiarActionPerformed

    private void formInternalFrameOpened(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameOpened

CalculosBD c = new CalculosBD();
c.cargarmp(cbx_mp);
    }//GEN-LAST:event_formInternalFrameOpened

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
if(WHERE.equals("")){
    JOptionPane.showMessageDialog(null, "Debe seleccionar una muestra previamente");
}else{
       CalculosBD calc = new CalculosBD();
       calc.cargarmpFORM_DT(cbx_mp, WHERE);
}
    
    }//GEN-LAST:event_jButton1ActionPerformed

    private void cbx_mpItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbx_mpItemStateChanged
int index= cbx_mp.getSelectedIndex();
if(WHERE.equals("")){
    JOptionPane.showMessageDialog(null, "Seleccione previamente una muestra");
}else{
if(index>0){
cargartablanucleos();   
contabilizartablanucleos();
DefaultTableModel dtm = (DefaultTableModel) tbl1.getModel();
CalculosBD calc = new CalculosBD();
calc.sumartotalesfila(dtm);
calc.sumartotalescolumna(dtm);
calc.porcentajesfilainferior(dtm);
}
}
    }//GEN-LAST:event_cbx_mpItemStateChanged

    private void tbl3MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tbl3MouseClicked
     String ids = tbl3.getValueAt(tbl3.getSelectedRow(), tbl3.getSelectedColumn()).toString();
     txt_expandir.setText(ids);
    }//GEN-LAST:event_tbl3MouseClicked

    private void tbl3KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tbl3KeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_tbl3KeyPressed

    private void btn_calcularComponentHidden(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_btn_calcularComponentHidden
        // TODO add your handling code here:
    }//GEN-LAST:event_btn_calcularComponentHidden

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

        Copiartabla copy = new Copiartabla();
        copy.copiartabla(tbl3, txt_muestra.getText(), WHERE, "Sistema de producción: códigos de piezas", "Materia prima: "+txt_mp_selec.getText());   
    }//GEN-LAST:event_btn_copiar1ActionPerformed

    private void copiar_modulo_nuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_copiar_modulo_nuActionPerformed
          Copiartabla copy = new Copiartabla();
        copy.copiartabla(tbl1, txt_muestra.getText(), WHERE, "Sistema de producción: módulos de negativos de lascado según subgrupos tipológicos de núcleos", "Materia prima: "+txt_mp_selec.getText());   

    }//GEN-LAST:event_copiar_modulo_nuActionPerformed
private void contabilizartablanucleos(){
    for (int i = 1; i < tbl1.getColumnCount(); i++) {
    for (int j = 0; j < tbl1.getRowCount(); j++) {
    int a = contarmodulosnucleos("n.LSMAY_MODULO", tbl1.getColumnName(i), WHERE, cbx_mp.getSelectedItem().toString(), tbl1.getValueAt(j, 0).toString());    
    int b = contarmodulosnucleos("n.LSMEN_MODULO", tbl1.getColumnName(i), WHERE, cbx_mp.getSelectedItem().toString(), tbl1.getValueAt(j, 0).toString());    
    int c = a+b;
    tbl1.setValueAt(c, j, i);
    }
    }
}

private int contarmodulosnucleos(String col, String subgrupo, String where, String MP,  String modulo){
int nummods=0;
ResultSet rs = null; 
     String consulta = "SELECT COUNT ("+col+")  FROM NUCLEOS n\n" +
"INNER JOIN\n" +
"FORMATIZADOS f\n" +
"ON f.ID_FORMATIZADOS = n.ID_FORMATIZADOS " +where + " AND (f.MP='"+MP+"') AND (n.SUBGRUPO='"+subgrupo+"') AND ("+col+"='"+modulo+"')  ";
        
     try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);

            if(rs.next()){
                nummods=rs.getInt("1");
            }       
        
        c.closeconnection();
        
        
        } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
     
    
    return nummods;
    
}
private void cargartablanucleos(){
   cbx_modulos.removeAllItems();
   cbx_modulos.addItem("Módulos");
   cbx_subgrusponucleos.removeAllItems();
   cbx_subgrusponucleos.addItem("Subgrupos tipológicos de núcleos");
   ArrayList<String> subgrupo = new ArrayList<>();
   subgrupo=getsubgrupos(WHERE, cbx_mp.getSelectedItem().toString());
    
    DefaultTableModel dtmnu = new DefaultTableModel();

        dtmnu.addColumn("Modulos de lascado mayor y menor");    
    for (int i = 0; i < subgrupo.size(); i++) {
        Object col = subgrupo.get(i);
        dtmnu.addColumn(col);
        cbx_subgrusponucleos.addItem(col.toString());
    }
    dtmnu.addColumn("Total");
    
    ArrayList<String> modulo = new ArrayList<>();
    modulo=getmodulos(WHERE, cbx_mp.getSelectedItem().toString());
    Object [] fila = new Object[dtmnu.getColumnCount()];
        for (int j = 0; j < modulo.size(); j++) {
            cbx_modulos.addItem(modulo.get(j));
            for (int i = 1; i < fila.length; i++) {
            fila[0]=modulo.get(j);
            
            fila[i]=0;
                }
            dtmnu.addRow(fila);
            }
    
tbl1.setModel(dtmnu);

    

}    
 private ArrayList<String> getsubgrupos (String where, String MP){
 
   ArrayList<String> subgrupo = new ArrayList<>();
     ResultSet rs = null; 
     String consulta = "SELECT DISTINCT (n.SUBGRUPO)  FROM NUCLEOS n\n" +
"INNER JOIN\n" +
"FORMATIZADOS f\n" +
"ON f.ID_FORMATIZADOS = n.ID_FORMATIZADOS " +where + " AND (f.MP='"+MP+"')  ";
         try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);

            while(rs.next()){
                subgrupo.add(rs.getString("SUBGRUPO"));
            }       
        
        c.closeconnection();
        
        
        } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
     
    
    return subgrupo;
}   
 private ArrayList<String> getmodulos (String where, String MP){
 
   ArrayList<String> modulo = new ArrayList<>();
     ResultSet rs = null; 
     String consulta = "SELECT DISTINCT (n.LSMAY_MODULO)  FROM FORMATIZADOS f\n" +
"INNER JOIN\n" +
"NUCLEOS n\n" +
"ON f.ID_FORMATIZADOS = n.ID_FORMATIZADOS " +where + " AND (f.MP='"+MP+"')  ";
      
     try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);

            while(rs.next()){
                modulo.add(rs.getString("LSMAY_MODULO"));
                
            }       
        
        c.closeconnection();
        
        
        } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }

         consulta = "SELECT DISTINCT (n.LSMEN_MODULO)  FROM FORMATIZADOS f\n" +
"INNER JOIN\n" +
"NUCLEOS n\n" +
"ON f.ID_FORMATIZADOS = n.ID_FORMATIZADOS " +where + " AND (f.MP='"+MP+"')  ";
       
         try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);

            while(rs.next()){
                modulo.add(rs.getString("LSMEN_MODULO"));
                
            }       
        
        c.closeconnection();
        
        
        } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }
     
        Set<String> hashSet = new HashSet<String>(modulo);
        modulo.clear();
        modulo.addAll(hashSet); 
    return modulo;
}   
 private ArrayList<String[]> getmodulosynucleos (String where, String MP){
 
   ArrayList<String[]> subgrupo = new ArrayList<>();
   String []registro= new String[2];
     ResultSet rs = null; 
     String consulta = "SELECT n.SUBGRUPO, f.MODULO_LONG_ANCHO  FROM NUCLEOS n\n" +
"INNER JOIN\n" +
"FORMATIZADOS f\n" +
"ON f.ID_FORMATIZADOS = n.ID_FORMATIZADOS " +where + " AND (f.MP='"+MP+"')  ";
         try {
            conexion c = new conexion();
            c.getConexion();
            
             rs = c.consulta(consulta);

            while(rs.next()){
                registro[0]=(rs.getString("SUBGRUPO"));
                registro[1]=(rs.getString("MODULO_LONG_ANCHO"));
                subgrupo.add(registro);
            }       
        
        c.closeconnection();
        
        
        } catch (SQLException ex) {
            Logger.getLogger(InteraccionesBD.class.getName()).log(Level.SEVERE, null, ex);
        }

    
    return subgrupo;
}   
private void generargraficofila1(){
    
 int a = Integer.parseInt(tbl2.getValueAt(tbl2.getSelectedRow(), 1).toString());
 int b = Integer.parseInt(tbl2.getValueAt(tbl2.getSelectedRow(), 2).toString());

 String Tamaño = tbl2.getValueAt(tbl2.getSelectedRow(), 0).toString();

String titulo = "Formas base-utiles y Cicatrices en núcleos de tamaño: " +Tamaño;

try{
    DefaultCategoryDataset ds = new DefaultCategoryDataset();
    ds.addValue(a, "Formas base-útiles", "");
    ds.addValue(b, "Cicatrices en núcleos", "");
    JFreeChart jf =ChartFactory.createBarChart3D(titulo, "Formas base y cicatrices núcleos", "Cantidad", ds, PlotOrientation.HORIZONTAL, true, true, true);

    
    CategoryPlot barchrt = jf.getCategoryPlot();
    barchrt.setRangeGridlinePaint(Color.ORANGE);
    ChartPanel barpanel = new ChartPanel(jf);
    jpanel.removeAll();
    jpanel.add(barpanel, BorderLayout.CENTER);
    jpanel.validate();
    

}catch (Exception ex){
    JOptionPane.showMessageDialog(null, "No se puede generar gráfico");
}
    
}
private void generargraficocolumna1(){
try{
    
  

    
String Columna = (tbl2.getColumnName(tbl2.getSelectedColumn()));  

String titulo = "Tamaños presentes en: " + Columna;
DefaultCategoryDataset ds = new DefaultCategoryDataset();

    
    for (int i = 0; i < tbl2.getRowCount(); i++) {
         int a = Integer.parseInt(tbl2.getValueAt(i, tbl2.getSelectedColumn()).toString());
         String Tamaño = tbl2.getValueAt(i, 0).toString();
         ds.addValue(a, Tamaño, "");
    }



 

    JFreeChart jf =ChartFactory.createBarChart3D(titulo, "Tamaños", "Cantidad", ds, PlotOrientation.HORIZONTAL, true, true, true);

    
    CategoryPlot barchrt = jf.getCategoryPlot();
    barchrt.setRangeGridlinePaint(Color.ORANGE);
    ChartPanel barpanel = new ChartPanel(jf);
    jpanel.removeAll();
    jpanel.add(barpanel, BorderLayout.CENTER);
    jpanel.validate();
    

}catch (Exception ex){
    JOptionPane.showMessageDialog(null, "No se puede generar gráfico segun col");
}
    
}    


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.ButtonGroup botones;
    private javax.swing.JButton btn_arbol;
    private javax.swing.JButton btn_calcular;
    private javax.swing.JButton btn_copiar;
    private javax.swing.JButton btn_copiar1;
    private javax.swing.JButton btn_info;
    private javax.swing.JComboBox<String> cbx_modulos;
    private javax.swing.JComboBox<String> cbx_mp;
    private javax.swing.JComboBox<String> cbx_subgrusponucleos;
    private javax.swing.JButton copiar_modulo_nu;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel14;
    private javax.swing.JLabel jLabel15;
    private javax.swing.JLabel jLabel16;
    private javax.swing.JLabel jLabel17;
    private javax.swing.JLabel jLabel18;
    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.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JScrollPane jScrollPane5;
    private javax.swing.JScrollPane jScrollPane6;
    private javax.swing.JPanel jpanel;
    private javax.swing.JPanel jpanel1;
    private javax.swing.JTable tbl1;
    private javax.swing.JTable tbl2;
    private javax.swing.JTable tbl3;
    private javax.swing.JTextArea txtSistemadeproduccion;
    private javax.swing.JTextArea txt_expandir;
    private javax.swing.JTextField txt_modulo;
    private javax.swing.JTextField txt_mp_selec;
    private javax.swing.JTextField txt_muestra;
    private javax.swing.JTextField txt_sentencia;
    private javax.swing.JTextField txt_subgruponu;
    // End of variables declaration//GEN-END:variables
}
