Java - Ayuda, mostrar imagen almacenada en mysql y mostrarla en un jlabel

 
Vista:
sin imagen de perfil

Ayuda, mostrar imagen almacenada en mysql y mostrarla en un jlabel

Publicado por juan gabriel (8 intervenciones) el 01/10/2015 00:28:18
Hola amigos, recien estoy empezando en java y me propuse a realizar una base de datos java y myql, pero resulta que me quede en un punto que no se como sulucionar he buscado en foros y videos pero no encuentro la solucion o el error.

es una pequeña aplicacion que registra un producto, y cada vez que registro un producto lo guarda en la base de datos y me muestra en un jtable los datos almacenados en dicha base de datos, en el jtable puedo seleacionar la fila y con clic derecho mostrar en los jtextfiel pero no logro mostrar la foto en un jlabel. acudo a sus ayudas y colaboracion, gracias. anexo proyecto - base de datos.

por favor si se tienen mejoras con mucho gusto son recibidas, estoy con las ganas de aprender.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
package conexion;
 
import clases.conectar;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.File;
import java.awt.*;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import static javax.print.attribute.Size2DSyntax.MM;
import javax.swing.table.DefaultTableModel;
import java.util.Date;
import java.text.ParseException;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
 
 
 
/**
 *
 * @author icore
 */
public class form_internal_productos extends javax.swing.JInternalFrame {
 
    /**
     * Creates new form form_internal_productos
     */
    public form_internal_productos() {
        initComponents();
        mostrardatos("");
 
        //ESTE CODIGO ES PARA EL JCOMBOBOX PARA VER LO QUE ESTA EN LA TABLA PROVEDOR       
        try {
        conectar con = new conectar();
        Connection reg = con.conexion();
        t_nombreprovedor.removeAllItems();
        String sql="";
        sql="SELECT * FROM provedor";
            Statement st = reg.createStatement();
            ResultSet rs = st.executeQuery(sql);
 
            while(rs.next()){
               t_nombreprovedor.addItem(rs.getString("nombreprovedor"));
 
            }
        } catch (SQLException ex) {
            Logger.getLogger(form_internal_productos.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
    File fichero;
 
     void mostrardatos (String valor) {
    DefaultTableModel modelo = new DefaultTableModel();
  modelo.addColumn("Serial");
  modelo.addColumn("Placa");
  modelo.addColumn("Tipo");
  modelo.addColumn("Marca");
  modelo.addColumn("Descripcion");
  modelo.addColumn("Cantidad");
  modelo.addColumn("Fecha Compra");
  modelo.addColumn("Agencia");
  modelo.addColumn("Imagen");
    tb_producto.setModel(modelo);
    //aqui es el codigo para la consulta del boton buscar
   String sql="";
    if(valor.equals("")) {
        sql="SELECT * FROM producto";
    }
    else {
        sql="SELECT * FROM producto WHERE serialproducto='"+valor+"'";
    }
    String []datos = new String [9];
        try {
            Statement st = reg.createStatement();
            ResultSet rs = st.executeQuery(sql);
            while(rs.next()){
 
                datos[0]=rs.getString("serialproducto");
                datos[1]=rs.getString("placaproducto");
                datos[2]=rs.getString("tipoproducto");
                datos[3]=rs.getString("marcaproducto");
                datos[4]=rs.getString("descripcionproducto");
                datos[5]=rs.getString("cantidadproducto");
                datos[6]=rs.getString("fechaproducto");
                datos[7]=rs.getString("nombreprovedor");
                ByteArrayOutputStream ouput = new ByteArrayOutputStream();
                InputStream isdatos = rs.getBinaryStream("fotoproducto");
                 int temp=isdatos.read();
        while(temp>=0)
        {
           ouput.write((char)temp);
           temp=isdatos.read();
 
        }
        Image imagen=Toolkit.getDefaultToolkit().createImage(ouput.toByteArray());
        imagen=imagen.getScaledInstance(110, 120, 1);
        lblfoto.setIcon(new ImageIcon(imagen));
               // datos[8]=rs.getString("fotoproducto");
                //String cod = t_imagenproducto.getText();
 
            //agregar la fila
      modelo.addRow(datos);
 
            }
        } catch (SQLException ex) {
            Logger.getLogger(form_internal_provedor.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(form_internal_productos.class.getName()).log(Level.SEVERE, null, ex);
        }
 
            }
 
    private void btnselecionarActionPerformed(java.awt.event.ActionEvent evt) {
 
        JFileChooser archivo = new JFileChooser();
 
        archivo.setAcceptAllFileFilterUsed(false);
        FileFilter Filtro1 = new FileNameExtensionFilter("JPG file","jpg");
        FileFilter Filtro2 = new FileNameExtensionFilter("PNG file","png");
        archivo.setFileFilter(Filtro1);
        archivo.addChoosableFileFilter(Filtro2);
        archivo.setDialogTitle("Abrir Archivo");
        File ruta = new File("D:/productos");
        archivo.setCurrentDirectory(ruta);
 
        int ventana = archivo.showOpenDialog(null);
 
        if(ventana == JFileChooser.APPROVE_OPTION)
            {
 
                File file = archivo.getSelectedFile();
                t_imagenproducto.setText(String.valueOf(file));
                Image foto = getToolkit().getImage(t_imagenproducto.getText());
                foto = foto.getScaledInstance(210, 210, Image.SCALE_DEFAULT);
                lblfoto.setIcon(new ImageIcon(foto));
        }
    }
 
    private void t_imagenproductoActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        JTextField txtnomimagen = new JTextField(5);
    }
 
    private void t_nombreprovedorActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }
 
    private void b_registrarActionPerformed(java.awt.event.ActionEvent evt) {
 
        String sql;
       // fotoproducto=t_imagenproducto.getText();
 
        sql="INSERT INTO producto (serialproducto,placaproducto,tipoproducto,marcaproducto,descripcionproducto,cantidadproducto,fechaproducto,nombreprovedor,fotoproducto) VALUES (?,?,?,?,?,?,?,?,?)";
        try {
        FileInputStream imagenproducto;
        PreparedStatement pst=reg.prepareStatement(sql);
            pst.setString(1,t_serialproducto.getText());
            pst.setString(2,t_placaproducto.getText());
            pst.setString(3,t_tipoproducto.getText());
            pst.setString(4,t_marcaproducto.getText());
            pst.setString(5,t_descripcionproducto.getText());
            pst.setString(6,t_cantidadproducto.getText());
            pst.setString(7,((JTextField)t_fechaproducto.getDateEditor().getUiComponent()).getText());
            pst.setString(8,t_nombreprovedor.getSelectedItem().toString());
            pst.setString(9, t_imagenproducto.getText());
            imagenproducto = new FileInputStream(t_imagenproducto.getText());
            pst.setBinaryStream(9,imagenproducto);
 
 
 
            int n=pst.executeUpdate();
           if (n>0){
           JOptionPane.showMessageDialog(null,"Registrado con exito");
           //mostrardatos("");
           }
       //  t_imagenproducto.setText(null);
       //  lblfoto.setIcon(null);
 
 
        }
          catch (SQLException ex) {
            Logger.getLogger(form_internal_productos.class.getName()).log(Level.SEVERE, null, ex);
         } catch (FileNotFoundException ex) {
            Logger.getLogger(form_internal_productos.class.getName()).log(Level.SEVERE, null, ex);
        }
 
 
    }
 
    private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
         int fila = tb_producto.getSelectedRow();
        if (fila>=0) {
            t_serialproducto.setText(tb_producto.getValueAt(fila, 0).toString());
            t_placaproducto.setText(tb_producto.getValueAt(fila, 1).toString());
            t_tipoproducto.setText(tb_producto.getValueAt(fila, 2).toString());
            t_marcaproducto.setText(tb_producto.getValueAt(fila, 3).toString());
            t_descripcionproducto.setText(tb_producto.getValueAt(fila, 4).toString());
            t_cantidadproducto.setText(tb_producto.getValueAt(fila, 5).toString());
            // AQUI PARA MOSTRAR EL DATO DE FECHA DE LA TABLA JAVA EN UN JDATECHOOSER
            SimpleDateFormat formatodeltexto = new SimpleDateFormat("yyyy-MM-dd");
            String fecha = tb_producto.getValueAt(fila, 6).toString().trim();
            Date dato = null;
            try {
                dato = formatodeltexto.parse(fecha);
            }
            catch (ParseException e) {
            e.printStackTrace();
            }
            t_fechaproducto.setDate(dato);
            /////////////////////////HASTA AQUI//////////////////////////
           // t_imagenproducto.setText(tb_producto.getValueAt(fila, 7).toString());
            String img=tb_producto.getValueAt(fila, 8).toString();
            t_imagenproducto.setText(img);
            Image foto = getToolkit().getImage(img);
            foto= foto.getScaledInstance(210, 210, 1);
            lblfoto.setIcon(new ImageIcon(foto));
 
 
        }
        else {
            JOptionPane.showMessageDialog(null,"Selecione una fila para Editar");
        }
    }
 
conectar con = new conectar();
 Connection reg = con.conexion();
}
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
sin imagen de perfil

Ayuda, mostrar imagen almacenada en mysql y mostrarla en un jlabel

Publicado por juan gabriel (8 intervenciones) el 02/10/2015 20:05:21
Amigo, muchas gracias funciona perfecto, verificare cual fue la correcion. gracias por su colaboracion.
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar