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

import java.awt.Font;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.ImageIcon;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.table.TableColumn;
import puntocassa.utils.Utils;

/**
 *
 * @author Marco
 */
public class FrmProdotti extends javax.swing.JFrame {

private PuntoCassa frmPuntoCassa;


   public int HFont=15;
   private int AltControlli=100;
   private int LargControlli=100;
   private int AltRigaGriglia=0;
   
    /**
     * Creates new form frm
     */
    public FrmProdotti(PuntoCassa frm,String imgPath) {

        frmPuntoCassa=frm;
        frmPuntoCassa.setEnabled(false);
        //KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(frmPuntoCassa.keyDispatcher);  
        frmPuntoCassa.addRemoveKeyDispatcher(false);
        initComponents();

        String startDir = System.getProperty("user.dir");
        File IconaApp = new File(startDir + "/risorse/logo.png");
        if (IconaApp.exists()) {

            ImageIcon icon = new ImageIcon(startDir + "/risorse/logo.png");
            this.setIconImage(icon.getImage());
        }
        
        ImageIcon icon = new ImageIcon(imgPath +"freccia_down.jpg");
        Image img = icon.getImage() ;  
        Image newimg = img.getScaledInstance(50,50,java.awt.Image.SCALE_SMOOTH ) ;  
        icon = new ImageIcon(newimg);  
        jbtnGiu.setIcon(icon);
      
        ImageIcon icon2 = new ImageIcon(imgPath +"freccia_up.jpg");
        Image img2 = icon2.getImage() ;   
        Image newimg2 = img2.getScaledInstance(50,50,java.awt.Image.SCALE_SMOOTH ) ;  
        icon2 = new ImageIcon(newimg2);
        jbtnSu.setIcon(icon2);

        // --------------------------------------------------------------------
        // ** creo evento click jTblStudenti
        // --------------------------------------------------------------------
        jTblProdotti.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {

                if (e.getClickCount() == 1) {
                             //JTable target = (JTable) e.getSource();
                    //int row = target.getSelectedRow();
                    //int column = target.getSelectedColumn();
//                    jBtnOKActionPerformed(null);
                }
            }
        });
        CaricaCombo("Select nome,id from categorie_prodotti union select ' ' as nome,0 as id from categorie_prodotti order by nome", "nome", "id", jCmbCat);
    }

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

        pnl1 = new javax.swing.JPanel();
        jScrollPane3 = new javax.swing.JScrollPane();
        jTblProdotti = new javax.swing.JTable();
        jLblTitolo = new javax.swing.JLabel();
        jbtnAggiungi = new javax.swing.JButton();
        lblCognome = new javax.swing.JLabel();
        jtxtCodice = new javax.swing.JTextField();
        jBtnCerca = new javax.swing.JButton();
        jbtnAnnulla2 = new javax.swing.JButton();
        jCmbCat = new javax.swing.JComboBox();
        lblCognome1 = new javax.swing.JLabel();
        jtxtProdotto = new javax.swing.JTextField();
        lblCognome2 = new javax.swing.JLabel();
        jbtnSu = new javax.swing.JButton();
        jbtnGiu = new javax.swing.JButton();
        jbtnElimina = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Cerca Prodotto");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

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

            }
        ));
        jScrollPane3.setViewportView(jTblProdotti);

        jLblTitolo.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLblTitolo.setForeground(new java.awt.Color(255, 0, 0));
        jLblTitolo.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        jLblTitolo.setText("Cerca Prodotti");

        jbtnAggiungi.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jbtnAggiungi.setText("Aggiungi Prodotto");
        jbtnAggiungi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAggiungiActionPerformed(evt);
            }
        });

        lblCognome.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        lblCognome.setText("Categoria:");

        jtxtCodice.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jtxtCodice.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jtxtCodiceFocusGained(evt);
            }
        });
        jtxtCodice.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtxtCodiceMouseClicked(evt);
            }
        });

        jBtnCerca.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jBtnCerca.setText("Cerca");
        jBtnCerca.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jBtnCercaActionPerformed(evt);
            }
        });

        jbtnAnnulla2.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jbtnAnnulla2.setText("Annulla");
        jbtnAnnulla2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnAnnulla2ActionPerformed(evt);
            }
        });

        jCmbCat.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jCmbCat.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));

        lblCognome1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        lblCognome1.setText("Codice:");

        jtxtProdotto.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jtxtProdotto.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                jtxtProdottoFocusGained(evt);
            }
        });
        jtxtProdotto.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtxtProdottoMouseClicked(evt);
            }
        });

        lblCognome2.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        lblCognome2.setText("Prodotto:");

        jbtnSu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnSuActionPerformed(evt);
            }
        });

        jbtnGiu.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnGiuActionPerformed(evt);
            }
        });

        jbtnElimina.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jbtnElimina.setText("Elimina Prodotto");
        jbtnElimina.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jbtnEliminaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout pnl1Layout = new javax.swing.GroupLayout(pnl1);
        pnl1.setLayout(pnl1Layout);
        pnl1Layout.setHorizontalGroup(
            pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnl1Layout.createSequentialGroup()
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnl1Layout.createSequentialGroup()
                        .addComponent(lblCognome)
                        .addGap(0, 180, Short.MAX_VALUE))
                    .addComponent(jCmbCat, 0, 274, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblCognome1)
                    .addComponent(jtxtCodice, javax.swing.GroupLayout.PREFERRED_SIZE, 130, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(lblCognome2)
                    .addGroup(pnl1Layout.createSequentialGroup()
                        .addComponent(jtxtProdotto, javax.swing.GroupLayout.DEFAULT_SIZE, 121, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jBtnCerca, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtnAnnulla2, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnl1Layout.createSequentialGroup()
                .addComponent(jLblTitolo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(8, 8, 8))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnl1Layout.createSequentialGroup()
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(pnl1Layout.createSequentialGroup()
                        .addComponent(jbtnAggiungi, javax.swing.GroupLayout.PREFERRED_SIZE, 261, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jbtnElimina, javax.swing.GroupLayout.PREFERRED_SIZE, 261, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jScrollPane3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtnSu, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnGiu, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );
        pnl1Layout.setVerticalGroup(
            pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnl1Layout.createSequentialGroup()
                .addComponent(jLblTitolo, javax.swing.GroupLayout.PREFERRED_SIZE, 25, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(lblCognome1)
                        .addComponent(lblCognome))
                    .addComponent(lblCognome2)
                    .addGroup(pnl1Layout.createSequentialGroup()
                        .addGap(21, 21, 21)
                        .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(jCmbCat, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(jbtnAnnulla2))
                            .addComponent(jBtnCerca, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jtxtCodice)
                            .addComponent(jtxtProdotto))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
                    .addGroup(pnl1Layout.createSequentialGroup()
                        .addComponent(jbtnSu, javax.swing.GroupLayout.PREFERRED_SIZE, 55, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jbtnGiu, javax.swing.GroupLayout.PREFERRED_SIZE, 53, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnl1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jbtnAggiungi, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jbtnElimina, javax.swing.GroupLayout.PREFERRED_SIZE, 30, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(pnl1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(pnl1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void ClearTable(MyTableModel model) {
        try {
            for (Integer i = model.getRowCount() - 1; i >= 0; i--) {
                model.deleteRow(i);
            }
        } catch (Exception e) {
        }
    }
    private void Tastiera(JTextField jTxt,Integer MyX,Integer MyY){
    
        MyKeyBoard myk=new MyKeyBoard(this,false);
        myk.txt=jTxt;
        myk.parent=this;
        Rectangle s=this.getBounds();
        Rectangle s2=jTxt.getBounds();
        Integer l=s.x+s2.x+MyX;
        if(l+800>s.x+s.width){l=s.x+s.width-800;}
        myk.setBounds(l,s.y+s2.y+60+MyY, 800, 300);
        myk.setVisible(true);

    }
    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
        try{
            frmPuntoCassa.setEnabled(true);
            //KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(frmPuntoCassa.keyDispatcher);
            frmPuntoCassa.addRemoveKeyDispatcher(true);
            frmPuntoCassa.toFront();
            frmPuntoCassa.repaint();
            frmPuntoCassa=null;
            this.dispose();
        }catch(Exception ex){}
    }//GEN-LAST:event_formWindowClosed

    private void jbtnAggiungiActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAggiungiActionPerformed
        MyTableModel model = new MyTableModel();
        model = (MyTableModel) jTblProdotti.getModel();
        Long cod = 0L;
        if (jTblProdotti.getSelectedRow() >= 0) {
            cod = Long.parseLong(model.getValueAt(jTblProdotti.getSelectedRow(), 0).toString());
            Boolean presente = Boolean.parseBoolean(model.getValueAt(jTblProdotti.getSelectedRow(), 4).toString());
            if (presente == false) {
                MyInsert("Insert into Catalogo_punti_cassa (id,id_prodotto,id_punto_cassa,flag_locale) values(-1," + cod + "," + frmPuntoCassa.idPuntoCassa + ",1)");
                frmPuntoCassa.caricaDati("PRODOTTI", "-1");
                this.dispose();
            }

        }

    }//GEN-LAST:event_jbtnAggiungiActionPerformed
    private Boolean MyInsert(String Query) {
        Boolean res=false;
        try {
            Connection dbConnection = DriverManager.getConnection(frmPuntoCassa.dbStringa, frmPuntoCassa.dbUsername, frmPuntoCassa.dbPassword);  
            Statement st = dbConnection.createStatement();
            ResultSet rs = st.executeQuery(Query);
            rs.close();
            st.close();
            dbConnection.close();
            res=true;
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(this, "Errore MySelect ['" + e.getMessage() + " " + Query + "']");
            
        }
        return res;
    }
    private void jtxtCodiceFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtxtCodiceFocusGained
        Tastiera(evt);
//        MyApplication MyA = new MyApplication();
//        if (MyA.TastieraVideo) {
//            if (MyA.UltimoTxt.equalsIgnoreCase(evt.getComponent().toString())) {
//                MyA.UltimoTxt = " ";
//            } else {
//                MyA.UltimoTxt = evt.getComponent().toString();
//                Tastiera((JTextField) evt.getComponent(), 0, 0);
//            }
//        }
    }//GEN-LAST:event_jtxtCodiceFocusGained

    private void jBtnCercaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jBtnCercaActionPerformed
//        if (jtxtProdotto.getText().trim().length()<=0){
//            JOptionPane.showMessageDialog(this, "Inserire la descrizione del prodotto!","Attenzione",JOptionPane.INFORMATION_MESSAGE);
//            return;
//        }

        Aggiorna();
    }//GEN-LAST:event_jBtnCercaActionPerformed

    private void jbtnAnnulla2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnAnnulla2ActionPerformed
        //        ClearTable((MyTableModel)jTblStudenti.getModel());

//        frmPuntoCassa.setEnabled(true);
//        frmPuntoCassa=null;
        this.dispose();

    }//GEN-LAST:event_jbtnAnnulla2ActionPerformed

    private void jtxtProdottoFocusGained(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_jtxtProdottoFocusGained
        Tastiera(evt);
    }//GEN-LAST:event_jtxtProdottoFocusGained

    private void jbtnSuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnSuActionPerformed
        // TODO add your handling code here:
        if(jTblProdotti.getSelectedRow()>0){
            jTblProdotti.setRowSelectionInterval(jTblProdotti.getSelectedRow()-1, jTblProdotti.getSelectedRow()-1);
            jTblProdotti.scrollRectToVisible(new Rectangle(jTblProdotti.getCellRect(jTblProdotti.getSelectedRow(), 0, true)));
        }
    }//GEN-LAST:event_jbtnSuActionPerformed

    private void jbtnGiuActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnGiuActionPerformed
        // TODO add your handling code here:
        if(jTblProdotti.getSelectedRow()<jTblProdotti.getRowCount()-1){
            jTblProdotti.setRowSelectionInterval(jTblProdotti.getSelectedRow()+1, jTblProdotti.getSelectedRow()+1);
            jTblProdotti.scrollRectToVisible(new Rectangle(jTblProdotti.getCellRect(jTblProdotti.getSelectedRow(), 0, true)));
        }
        
    }//GEN-LAST:event_jbtnGiuActionPerformed

    private void jtxtCodiceMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtxtCodiceMouseClicked
        Tastiera(evt);
    }//GEN-LAST:event_jtxtCodiceMouseClicked

    private void jtxtProdottoMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtxtProdottoMouseClicked
       Tastiera(evt);
    }//GEN-LAST:event_jtxtProdottoMouseClicked

    private void jbtnEliminaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnEliminaActionPerformed
        MyTableModel model = new MyTableModel();
        model = (MyTableModel) jTblProdotti.getModel();
        Long cod = 0L;
        if (jTblProdotti.getSelectedRow() >= 0) {
            cod = Long.parseLong(model.getValueAt(jTblProdotti.getSelectedRow(), 0).toString());
            Boolean presente = Boolean.parseBoolean(model.getValueAt(jTblProdotti.getSelectedRow(), 4).toString());
            if (presente) {
                MyInsert("Delete Catalogo_punti_cassa where id_prodotto=" + cod + " and id_punto_cassa=" + frmPuntoCassa.idPuntoCassa);
                frmPuntoCassa.caricaDati("PRODOTTI", "-1");
                this.dispose();
            }

        }
    }//GEN-LAST:event_jbtnEliminaActionPerformed
       private void Tastiera(java.awt.event.MouseEvent evt) {
        MyApplication MyA = new MyApplication();
        if (MyA.tastieraVideo) {
            if (MyA.ultimoTxt.equalsIgnoreCase(evt.getComponent().toString())) {
                MyA.ultimoTxt = " ";
            } else {
                MyA.ultimoTxt = evt.getComponent().toString();
                Tastiera((JTextField) evt.getComponent(), 0, 0);
            }
        }
    }
    //java.awt.event.FocusEvent
    private void Tastiera(java.awt.event.FocusEvent evt) {
        MyApplication MyA = new MyApplication();
        if (MyA.tastieraVideo) {
            if (MyA.ultimoTxt.equalsIgnoreCase(evt.getComponent().toString())) {
                MyA.ultimoTxt = " ";
            } else {
                MyA.ultimoTxt = evt.getComponent().toString();
                Tastiera((JTextField) evt.getComponent(), 0, 0);
            }
        }
    }
    private void QueryDati(String Query,String QueryCount,String[] Colonne,String[] ColType, JTable jTbl,Boolean Editable){
     try{
        MyApplication MyA=new MyApplication();
        MyTableModel model = new MyTableModel( );
        model.setColumname(Colonne);
        
//        model.setEditable(Editable);
//        int [] colBool=new int[1];
//        colBool[0]=7;
//        model.setColBoolean(colBool);
//        int[] cols=new int[1];
//        cols[0]=7;
//        model.setColModificabile(cols);
        int rowCount=Integer.parseInt(Utils.mySelect(QueryCount, "righe", frmPuntoCassa));
        Object[][] data = RowData(Query, Colonne,ColType,rowCount);
        model.setData(data);

        try{jTbl.setModel(model);}catch(Exception e){}
        jTbl.setAutoCreateColumnsFromModel(true);

        jTbl.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        jTbl.getTableHeader().setFont(new Font("Tahoma", Font.BOLD, 16));
        jTbl.setFont(new Font("Tahoma", 0, 16));
        
        
        TableColumn column = jTbl.getColumn("id");
        column.setMinWidth(0);
        column.setMaxWidth(0);
        column.setWidth(0);
        column.setPreferredWidth(0);
        
        TableColumn column1 = jTbl.getColumn("Prodotto");
        column1.setPreferredWidth(380);
        column1.setWidth(380);
//        TableColumn column2 = jTbl.getColumn("Codice");
//        column2.setPreferredWidth(20);
        
        model.fireTableDataChanged();
        
        doLayout();
     }catch(NumberFormatException e){
     
        System.out.println("Query: " + e.getMessage());
     }
     
    } 
   private void Aggiorna() {
        try {
            String From=" from prodotti p, categorie_prodotti c ";
            String Where = "  WHERE p.id_categoria = c.id ";
            if (jtxtCodice.getText().trim().length() > 0) {
                Where = Where + " and upper(p.codice) like '" + jtxtCodice.getText().trim().replace("'", "''").toUpperCase() + "%' ";
            }
            if (jtxtProdotto.getText().trim().length() > 0) {
                Where = Where + " and upper(p.nome) like '%" + jtxtProdotto.getText().trim().replace("'", "''").toUpperCase() + "%' ";
            }
            
            ComboItem c = new ComboItem(null, null);
            c = (ComboItem) jCmbCat.getSelectedItem();
            
            if (c.getKey() > 0) {
                Where = Where + " and p.id_categoria = " + c.getKey();
            }
            String[] Col = {"id","Categoria","Codice","Prodotto","Presente"};
            String[] ColType = {"long", "text","text","text","boolean"};
            String QueryCount="Select count(*) as righe " + From + Where;
            QueryDati("select p.id,c.nome as categoria,p.codice, p.nome as prodotto, prodotto_in_catalogo (p.id, " + frmPuntoCassa.idPuntoCassa + ") as presente " + From + Where + " order by c.nome,p.nome", QueryCount, Col, ColType, jTblProdotti, false);
            
            //jTblStudenti.getColumn("Drawing").setPreferredWidth(200);
            

            
            //Font f=new Font("Tahoma",0,HFont); 
            Font f=new Font("Tahoma",0,20);         
            jTblProdotti.setFont(f);
            jTblProdotti.setFont(f);
            if(AltRigaGriglia==0){AltRigaGriglia=jTblProdotti.getRowHeight();}
//            txtUsername.setSize(CalcolaLarghezzaAltezza(txtUsername.getWidth(),LargControlli), CalcolaLarghezzaAltezza(txtUsername.getHeight(),AltControlli));   
 
            //jTblProdotti.setRowHeight(CalcolaLarghezzaAltezza(AltRigaGriglia,AltControlli));
            jTblProdotti.setRowHeight(25);
            //ClearTable((MyTableModel)jTblTessere.getModel());
            
            if (jTblProdotti.getRowCount() > 0) {
                jTblProdotti.setRowSelectionInterval(0, 0);
                
            }
            ///AggiornaTessera(0);


        } catch (Exception e) {
        }
    }
     private Integer CalcolaLarghezzaAltezza(Integer LarControllo,Integer Percentuale){
      Integer D = Percentuale - 100;
      if (D == 0) {
          return LarControllo;
      } else {
          Integer N = LarControllo + ((LarControllo * D) / 100);
          return N;
      }
  
  }
    public Object[][] RowData(String Query, String[] Cols, String[] ColType, int rowCount) {
        Object[][] rows = null;
        try {
            Connection dbConnection = DriverManager.getConnection(frmPuntoCassa.dbStringa, frmPuntoCassa.dbUsername, frmPuntoCassa.dbPassword);
            Statement st = dbConnection.createStatement();
            ResultSet rs = st.executeQuery(Query);
            rows = new Object[rowCount][];
            int r = 0;
            while (rs.next()) {
                Object[] row = new Object[Cols.length];
                for (int i = 0; i < Cols.length; i++) {
                    if (rs.getString(Cols[i].replace(" ", "_")) == null) {
                        row[i] = "";
                    } else {
                        row[i] = rs.getString(Cols[i].replace(" ", "_"));
                    }
                    switch (ColType[i]) {
                        case "text":
                            if (rs.getString(Cols[i].replace(" ", "_")) == null) {
                                row[i] = "";
                            } else {
                                row[i] = rs.getString(Cols[i].replace(" ", "_"));
                            }
                            break;
                        case "integer":
                            if (rs.getString(Cols[i].replace(" ", "_")) == null) {
                                row[i] = 0;
                            } else {
                                row[i] = rs.getInt(Cols[i].replace(" ", "_"));
                            }
                            break;
                        case "boolean":
                            if (rs.getString(Cols[i].replace(" ", "_")) == null) {
                                row[i] = false;
                            } else {
                                row[i] = rs.getBoolean(Cols[i].replace(" ", "_"));
                            }
                            break;
                        case "float":
                            if (rs.getString(Cols[i].replace(" ", "_")) == null) {
                                row[i] = 0.00;
                            } else {
                                String v = rs.getString(Cols[i].replace(" ", "_"));

                                row[i] = Float.parseFloat(v.replace(",", "."));
                            }

                            break;
                            
                         case "data":
                            row[i] = "";
                            if (rs.getString(Cols[i].replace(" ", "_")) != null) {
//                                Date d = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.ITALY).parse(rs.getString(Cols[i]));
                                //SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
                                String[] d= rs.getString(Cols[i].replace(" ", "_")).split("-");
                                if (d.length>=3){
                                    row[i] = d[2].trim().substring(0, 2) + "/" + d[1] + "/" + d[0];
                                }
                            }

                            break;
                    }

                }
                rows[r] = row;
                r++;
                /*int id = rs.getInt("id");
                 String  name = rs.getString("name");
                 int age  = rs.getInt("age");
                 String  address = rs.getString("address");
                 float salary = rs.getFloat("salary");*/

            }
            rs.close();
            st.close();
            dbConnection.close();

        } catch (SQLException | NumberFormatException e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        } finally {

            return rows;
        }

    }  
    /**
     * @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 ex) {
            java.util.logging.Logger.getLogger(FrmProdotti.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrmProdotti.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrmProdotti.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrmProdotti.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new FrmProdotti(null,null).setVisible(true);
            }
        });
    }
    private void CaricaCombo (String Query, String itemValue, String itemId, JComboBox cmb) {
        try {
            Connection dbConnection = DriverManager.getConnection(frmPuntoCassa.dbStringa, frmPuntoCassa.dbUsername, frmPuntoCassa.dbPassword);
            Connection c = dbConnection;
            Statement stmt = null;
            cmb.removeAllItems();
            stmt = c.createStatement();
            ResultSet rs = stmt.executeQuery(Query);
            int r = 0;
            while (rs.next()) {
                
                ComboItem row=new ComboItem(rs.getLong(itemId), rs.getString(itemValue)) ;
                cmb.addItem(row);

                r++;

            }
            rs.close();
            stmt.close();
            dbConnection.close();

        } catch (SQLException e) {
            System.err.println(e.getClass().getName() + ": " + e.getMessage());
        } 

    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBtnCerca;
    private javax.swing.JComboBox jCmbCat;
    private javax.swing.JLabel jLblTitolo;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTblProdotti;
    private javax.swing.JButton jbtnAggiungi;
    private javax.swing.JButton jbtnAnnulla2;
    private javax.swing.JButton jbtnElimina;
    private javax.swing.JButton jbtnGiu;
    private javax.swing.JButton jbtnSu;
    private javax.swing.JTextField jtxtCodice;
    private javax.swing.JTextField jtxtProdotto;
    private javax.swing.JLabel lblCognome;
    private javax.swing.JLabel lblCognome1;
    private javax.swing.JLabel lblCognome2;
    private javax.swing.JPanel pnl1;
    // End of variables declaration//GEN-END:variables
}
