Java - Mostrar en un LABEL una imagen ya guardada en MySQL

 
Vista:
Imágen de perfil de erick edgardo
Val: 34
Ha aumentado 1 puesto en Java (en relación al último mes)
Gráfica de Java

Mostrar en un LABEL una imagen ya guardada en MySQL

Publicado por erick edgardo (14 intervenciones) el 30/04/2018 19:19:58
ESTO ES TODO EL CODIGO, HAY UNA PARTE QUE AUN NO LA HE TERMINADO DE PROGRAMAR (editar datos e imagen), pero eso lo solucionare despues, Por ahora espero puedan ayudarme para solucionar mi problema sobre como hacer que al seleccionar el dato en la tabla, esta envie la foto directo al Jlabel.

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
package clases;
 
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileNameExtensionFilter;
import javax.swing.table.DefaultTableModel;
 
 
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 238, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnguardar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnbuscar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btneditar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnborrar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton1)
                        .addGap(120, 120, 120))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 488, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(23, 23, 23))))
        );
 
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 872, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, 511, Short.MAX_VALUE)
                .addGap(0, 0, 0))
        );
 
        pack();
    }// </editor-fold>                        
 
 
 
 
 
    private void btnbuscarActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        try{
            Class.forName("com.mysql.jdbc.Driver");
            Connection conexion = DriverManager.getConnection("jdbc:mysql://localhost/abarrotes","root","");
            Statement stm = conexion.createStatement();
            ResultSet rst = stm.executeQuery("SELECT * FROM frutasyverduras");
            ResultSetMetaData rsMd = rst.getMetaData();
            int numeroColumnas = rsMd.getColumnCount();
            DefaultTableModel modelo = new  DefaultTableModel();
            this.tbconsultas.setModel(modelo);
            for (int x=1 ; x <= numeroColumnas ; x++){
                modelo.addColumn (rsMd.getColumnLabel(x));
            }
            while (rst.next()){
                Object [] fila = new Object  [numeroColumnas];
                for (int y=0 ; y < numeroColumnas ; y++){
                    fila [y]=rst.getObject(y+1);
                }
                modelo.addRow(fila);
            }
        }
        catch (ClassNotFoundException ce){
            ce.printStackTrace();
        }
        catch (SQLException se){
            se.printStackTrace();
        }
    }
 
    private void ventatxtActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }
 
    private void compratxtActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }
 
    private void btneditarActionPerformed(java.awt.event.ActionEvent evt) {
        // AUN NO TERMINO DE PROGRAMAR ESTO :D
         try {
            PreparedStatement pst = cn.prepareStatement("UPDATE frutasyverduras SET Nom_Producto='"+ nomprodtxt.getText()+"',Preci_compra='"+compratxt.getText()+"',Preci_venta='"+ventatxt.getText()+"',Nom_Imagen='"+fototxt.getText()+"',apellido_p='"+apellidoptxt.getText()+"',apellido_m='"+apellidomtxt.getText()+"',telefono='"+telefonotxt.getText()+"',cargo='"+cargotxt.getSelectedItem()+"' WHERE ID_usuario="+idtxt.getText()+"");
            pst.execute();
 
 
 
 
        } catch (Exception e) {
            System.out.print(e.getMessage());
        }
 
        nomprodtxt.setText("");
        compratxt.setText("");
        ventatxt.setText("");
        fototxt.setText("");
 
    }
 
    private void btnguardarActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        try {
            // Creamos una variable para poder obtener la cantidad de bytes de una imagen
            FileInputStream  archivofoto;
            PreparedStatement pst = cn.prepareStatement("INSERT INTO frutasyverduras(Nom_Producto,Preci_compra,Preci_venta,nom_imagen,imagen) VALUES (?,?,?,?,?)");
 
 
            pst.setString(1, nomprodtxt.getText());
            pst.setString(2, compratxt.getText());
            pst.setString(3, ventatxt.getText());
            pst.setString(4, fototxt.getText());
 
 
 
            // pero para ello necesitamos conocer la ruta de la imagen
            archivofoto = new FileInputStream(fototxt.getText());
            //SetBinaryStream permite almacenar cantidad de bytes en la base de datos
            pst.setBinaryStream(5, archivofoto);
 
            int i=pst.executeUpdate();
            if(i>0){
            JOptionPane.showMessageDialog(null, "Se guardo correctamente");
           }
 
 
               fototxt.setText(null);
               lblimagen.setIcon(null);
        } catch (SQLException ex) {
            Logger.getLogger(productos_consultas.class.getName()).log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            Logger.getLogger(frutas_verduras.class.getName()).log(Level.SEVERE, null, ex);
        }
 
    }
 
    private void btnborrarActionPerformed(java.awt.event.ActionEvent evt) {
 
        int fila = tbconsultas.getSelectedRow();
        String id="";
        id=tbconsultas.getValueAt(fila, 0).toString();
        try {
            PreparedStatement pst = cn.prepareStatement("DELETE FROM frutasyverduras WHERE Usuario='"+id+"'");
            pst.executeUpdate();
 
            codproductotxt.setText("");
            nomprodtxt.setText("");
 
 
 
            compratxt.setText("");
            ventatxt.setText("");
        } catch (Exception e) {
        }
    }
 
    private void btnexaminarActionPerformed(java.awt.event.ActionEvent evt) {
 
       JFileChooser archivo = new JFileChooser();
 
        FileNameExtensionFilter filtro = new FileNameExtensionFilter("Formatos de Archivos JPEG(*.JPG;*.JPEG)", "jpg","jpeg");
 
        archivo.addChoosableFileFilter(filtro);
 
        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();
 
            fototxt.setText(String.valueOf(file));
 
            Image foto= getToolkit().getImage(fototxt.getText());
 
            foto= foto.getScaledInstance(163, 168, Image.SCALE_DEFAULT);
 
            lblimagen.setIcon(new ImageIcon(foto));
        }
    }
 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
        this.dispose();
    }
 
    private void tbconsultasMouseClicked(java.awt.event.MouseEvent evt) {
        // TODO add your handling code here:
                int rect=this.tbconsultas.getSelectedRow();
        this.nomprodtxt.setText(this.tbconsultas.getValueAt(rect, 0).toString());
        this.compratxt.setText(this.tbconsultas.getValueAt(rect, 1).toString());
        this.ventatxt.setText(this.tbconsultas.getValueAt(rect,2).toString());
        this.fototxt.setText(this.tbconsultas.getValueAt(rect, 3).toString());
        String img=tbconsultas.getValueAt(rect, 4).toString();
        Image foto = getToolkit().getImage(img);
        foto= foto.getScaledInstance(110, 110, 1);
        lblimagen.setIcon(new ImageIcon(foto));
        this.codproductotxt.setText(this.tbconsultas.getValueAt(rect, 5).toString());
 
    }
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