Load an image from the database with the MouseClicked event of a jtable in Java

0

I'm starting in java and I decided to create a java and mysql database, but it turns out that I stayed at a point that I do not know how to solve. I have searched forums and videos but I can not find the solution or the error.

It is a small application that registers a product, and every time you register a product it stores it in the database. The data is loaded in jtable, when selecting a row, these are loaded in jtext. What I can not do is load the image (which is in the data base) into a jlabel. The problem is in the mousecliked jtable event

Of course, I appreciate your help.

Greetings.

package Presentacion;

import Configuration.AdministratorConfiguration; import Data.Product; import Data.dateTable; import java.awt.Image; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.InputStream; import java.sql.Blob; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import javax.imageio.ImageIO; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableRowSorter;

public class gestionProduct extends javax.swing.JFrame {     Product product = new Product ();     DefaultTableModel model;     TableRowSorter jTblProductFil;     BufferedImage img = null;     private FileInputStream fileImage;     private int lengthBytes;     // FileInputStream fis;

public gestionProducto() 
{
    initComponents();
    this.setLocationRelativeTo(null);
    cargarTabla();
}

private void ocultarColumnas(JTable tbl, int columna[])
{
    for (int i = 0; i < columna.length; i++) 
    {
        tbl.getColumnModel().getColumn(columna[i]).setMaxWidth(0);
        tbl.getColumnModel().getColumn(columna[i]).setMinWidth(0);
        tbl.getTableHeader().getColumnModel().getColumn(columna[i]).setMaxWidth(0);
        tbl.getTableHeader().getColumnModel().getColumn(columna[i]).setMinWidth(0);
    }
}

private void cargarTabla()
{
    try 
    {
        Connection miComando = AdministradorConfiguracion.obtenerComandoMySql();
        CallableStatement obtenerProductos = miComando.prepareCall("call obtener_productos()");
        ResultSet rs = obtenerProductos.executeQuery();
        jTblProducto.setDefaultRenderer(Object.class, new fechaTabla());
        ResultSetMetaData rsmd = rs.getMetaData();
        String titulos[]= {"Nro Producto","Producto","Stock","Precio Costo","Precio Venta","Marca","Categoria","Proveedor",
                          "Descripcion","Fecha Vencimiento","Meses Restantes","Dias Restantes","Imagen"};
        Object[] fila = new Object[rsmd.getColumnCount()];
        modelo = new DefaultTableModel(null,titulos);
        while (rs.next()) 
        {
            fila[0] = rs.getInt("Nro Producto");
            fila[1] = rs.getString("Producto");
            fila[2] = rs.getInt("Stock");
            fila[3] = rs.getDouble("Precio Costo");
            fila[4] = rs.getDouble("Precio Venta");
            fila[5] = rs.getString("Marca");
            fila[6] = rs.getString("Categoria");
            fila[7] = rs.getString("Proveedor");
            fila[8] = rs.getString("Descripcion");
            fila[9] = rs.getDate("Fecha Vencimiento");
            fila[10] = rs.getInt("Meses Restantes");
            fila[11] = rs.getInt("Dias Restantes");
            Blob blob = rs.getBlob(13);
            if (blob != null) {
                byte[] data = blob.getBytes(1, (int) blob.length());
                try 
                {
                    img = ImageIO.read(new ByteArrayInputStream(data));
                    ImageIcon icono = new ImageIcon(img);
                    fila[12] = new JLabel(icono);
                } 
                catch (Exception ex) 
                {
                    System.out.println(ex.getMessage());
                }
            }
            else 
            {
                fila[12] = "Sin imagen";
            }
            modelo.addRow(fila);
        }
        jTblProducto.setModel(modelo);
        //jTblProducto.setRowHeight(64);
        contarFilas();
        ocultarColumnas(jTblProducto, new int[]{0,3,4,5,6,7,8,12});
    } 
    catch (Exception e) 
    {
        JOptionPane.showMessageDialog(null, "Error al intentar obtener los productos:\n"
            + e, "Error en la operación", JOptionPane.ERROR_MESSAGE);
    }
}

private void cargarTablaFil(String bus)
{
    try 
    {
        Connection miComando = AdministradorConfiguracion.obtenerComandoMySql();
        CallableStatement obtenerProductos = miComando.prepareCall("call buscar_producto(?)");
        ResultSet rs = obtenerProductos.executeQuery();
        jTblProducto.setDefaultRenderer(Object.class, new fechaTabla());
        ResultSetMetaData rsmd = rs.getMetaData();
        String titulos[]= {"Nro Producto","Producto","Stock","Precio Costo","Precio Venta","Marca","Categoria","Proveedor",
                          "Descripcion","Fecha Vencimiento","Meses Restantes","Dias Restantes","Imagen"};
        Object[] fila = new Object[rsmd.getColumnCount()];
        modelo = new DefaultTableModel(null,titulos);
        while (rs.next()) 
        {
            fila[0] = rs.getInt("Nro Producto");
            fila[1] = rs.getString("Producto");
            fila[2] = rs.getInt("Stock");
            fila[3] = rs.getDouble("Precio Costo");
            fila[4] = rs.getDouble("Precio Venta");
            fila[5] = rs.getString("Marca");
            fila[6] = rs.getString("Categoria");
            fila[7] = rs.getString("Proveedor");
            fila[8] = rs.getString("Descripcion");
            fila[9] = rs.getDate("Fecha Vencimiento");
            fila[10] = rs.getInt("Meses Restantes");
            fila[11] = rs.getInt("Dias Restantes");
            Blob blob = rs.getBlob(13);
            if (blob != null) {
                byte[] data = blob.getBytes(1, (int) blob.length());
                try 
                {
                    img = ImageIO.read(new ByteArrayInputStream(data));
                    ImageIcon icono = new ImageIcon(img);
                    fila[12] = new JLabel(icono);
                } 
                catch (Exception ex) 
                {
                    System.out.println(ex.getMessage());
                }
            }
            else 
            {
                fila[12] = "Sin imagen";
            }
            modelo.addRow(fila);
        }
        jTblProducto.setModel(modelo);
        //jTblProducto.setRowHeight(64);
        contarFilas();
        ocultarColumnas(jTblProducto, new int[]{0,3,4,5,6,7,8,12});
    } 
    catch (Exception e) 
    {
        JOptionPane.showMessageDialog(null, "Error al intentar obtener los productos:\n"
            + e, "Error en la operación", JOptionPane.ERROR_MESSAGE);
    }
}

private void sumarColumnas()
{
    double sumatoria = 0;
    double sumatoria1 = 0;
    int totalRow = jTblProducto.getRowCount();
    totalRow -= 1;
    for (int i = 0; i <= (totalRow); i++) 
    {
        sumatoria = Double.parseDouble(String.valueOf(jTblProducto.getValueAt(i, 0)));
    }
    sumatoria1 += sumatoria;
    jTxtTotal.setText(String.valueOf(sumatoria1));
}

private void contarFilas() 
{
    for (int i = 0; i <= jTblProducto.getRowCount(); i++) 
    {
        jTxtTotal.setText(String.valueOf(i));
    }
}

private void jTblProductMouseClicked (java.awt.event.MouseEvent evt) {
        int rowSelected = jTblProduct.getSelectedRow ();         model = (DefaultTableModel) jTblProducto.getModel ();         jTxtNameProd.setText (model.getValueAt (Selected row, 1) .toString ());         jTxtStock.setText (model.getValueAt (Selected row, 2) .toString ());         jTxtPrecioCos.setText (model.getValueAt (Selected row, 3) .toString ());         jTxtPriceVen.setText (model.getValueAt (Selected row, 4) .toString ());         jTxtMarca.setText (model.getValueAt (Selected row, 5) .toString ());         jTxtCategoria.setText (model.getValueAt (Selected row, 6) .toString ());         jTxtProvider.setText (model.getValueAt (Selected row, 7) .toString ());         jTxtDescription.setText (model.getValueAt (Selected row, 8) .toString ());         JtxtFechaVen.setText (model.getValueAt (Selected row, 9) .toString ());

    if(modelo.getValueAt(filaSeleccionada, 12) != null)
    {
        ImageIcon ima = (ImageIcon)modelo.getValueAt(filaSeleccionada, 12);
        Image imagen  = ima.getImage().getScaledInstance(jLblImagen.getWidth(),jLblImagen.getHeight(),Image.SCALE_SMOOTH);
        ImageIcon imagen1 = new ImageIcon(imagen);
        jLblImagen.setIcon(imagen1);
    }
}                                         

private void jTxtBuscarKeyTyped(java.awt.event.KeyEvent evt) {                                    
    jTxtBuscar.addKeyListener(new KeyAdapter() 
    {
        @Override
        public void keyReleased(KeyEvent e) 
        {
            if (!jTxtBuscar.getText().isEmpty()) 
            {
                cargarTablaFil(jTxtBuscar.getText());
                contarFilas();
                ocultarColumnas(jTblProducto, new int[]{0,3,4,5,6,7,8,12});
            } 
            else 
            {
                cargarTabla();
                contarFilas();
                ocultarColumnas(jTblProducto, new int[]{0,3,4,5,6,7,8,12});
            }
        }
    });
    jTblProductoFil = new TableRowSorter(modelo);
    jTblProducto.setRowSorter(jTblProductoFil);
    jTblProducto.setAutoCreateRowSorter(true);
}                                   

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

    /* Create and display the form */
    java.awt.EventQueue.invokeLater(new Runnable() {
        public void run() {
            new gestionProducto().setVisible(true);
        }
    });
}

// Variables declaration - do not modify                     
private javax.swing.JTextPane JtxtFechaVen;
private javax.swing.JButton jBtnEditar;
private javax.swing.JButton jBtnEliminar;
private javax.swing.JButton jBtnNuevo;
private javax.swing.JButton jBtnSalir;
private javax.swing.JLabel jLblCategoria;
private javax.swing.JLabel jLblDescripcion;
private javax.swing.JLabel jLblFechaVen;
private javax.swing.JLabel jLblImagen;
private javax.swing.JLabel jLblMarca;
private javax.swing.JLabel jLblPrecioCos;
private javax.swing.JLabel jLblPrecioVen;
private javax.swing.JLabel jLblProveedor;
private javax.swing.JLabel jLblStock;
private javax.swing.JLabel jLblTotal;
private javax.swing.JPanel jPnlFicha;
private javax.swing.JPanel jPnlProducto;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JScrollPane jScrollPane10;
private javax.swing.JScrollPane jScrollPane11;
private javax.swing.JScrollPane jScrollPane12;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane5;
private javax.swing.JScrollPane jScrollPane6;
private javax.swing.JScrollPane jScrollPane7;
private javax.swing.JScrollPane jScrollPane8;
private javax.swing.JScrollPane jScrollPane9;
private javax.swing.JTable jTblProducto;
private javax.swing.JTextPane jTxtBuscar;
private javax.swing.JTextPane jTxtCategoria;
private javax.swing.JTextPane jTxtDescripcion;
private javax.swing.JTextPane jTxtMarca;
private javax.swing.JTextPane jTxtNombreProd;
private javax.swing.JTextPane jTxtPrecioCos;
private javax.swing.JTextPane jTxtPrecioVen;
private javax.swing.JTextPane jTxtProveedor;
private javax.swing.JTextPane jTxtStock;
private javax.swing.JTextField jTxtTotal;
// End of variables declaration                   

}

    
asked by Charlees 11.08.2017 в 15:52
source

0 answers