Java - Ayuda con un boton

 
Vista:
Imágen de perfil de Carlos Manuel
Val: 5
Ha aumentado su posición en 6 puestos en Java (en relación al último mes)
Gráfica de Java

Ayuda con un boton

Publicado por Carlos Manuel (2 intervenciones) el 28/04/2021 11:17:40
Buenos dias,

acudo a vosotros, sabios, porque estoy muy perdido y no se por donde tirar.

Estoy aprendiendo a programar y mi primera eleccion ha sido JAVA. Para practicar lo aprendido me he metido a realizar un programa para clasificar y ordenar mi coleccion de cine y musica de casa. Para ello he creado una interfaz grafica y una base de datos en MySql.

Uno de los campos de la interfaz grafica es un buscador por ID de pelicula.
El problema esta en que el buscador me retorna todos los campos menos un campo caratula que es un JPanel.
El boton de añadir si que me añade absolutamente todo y al agregar dicha caratula me la muestra.

Os dejo el codigo del boton de buscar para ver si me podeis ayudar a localizar el error y subsanarlo, por favor.

Gracias!

private void btn_BuscarActionPerformed(java.awt.event.ActionEvent evt) {

Connection con = null;
try {
con = getConnection();
ps = (PreparedStatement) con.prepareStatement("SELECT * FROM dvd WHERE idDVD = ?");
ps.setString(1, txt_Id.getText());
rs = ps.executeQuery();


if (rs.next()) {
txt_Id.setText(rs.getString("idDVD"));
txt_Titulo.setText(rs.getString("Titulo"));
txt_Año.setText(rs.getString("Año"));
txt_Director.setText(rs.getString("Director"));
txt_Discos.setText(rs.getString("Discos"));
txt_Formato.setText(rs.getString("Formato"));
txt_Original.setText(rs.getString("Original"));
txt_Sinopsis.setText(rs.getString("Sinopsis"));

BufferedImage buffimg = null;
byte[] image = null;
while (rs.next()) {
image = rs.getBytes("Caratula");
InputStream img = rs.getBinaryStream(1);
try {
buffimg = ImageIO.read(img);
ImagenMySQL caratula = new ImagenMySQL(jpCaratula.getHeight(), jpCaratula.getWidth(), buffimg);
jpCaratula.add(caratula);
jpCaratula.repaint();
} catch (IOException ex) {
System.err.println(ex);
}
}
rs.close();

} else {
JOptionPane.showMessageDialog(null, "No existen registros para esa clave");
}

} catch (Exception e) {
System.err.println(e);
}

}
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
Imágen de perfil de Omar
Val: 77
Ha disminuido su posición en 8 puestos en Java (en relación al último mes)
Gráfica de Java

Ayuda con un boton

Publicado por Omar (24 intervenciones) el 29/04/2021 06:36:09
Bien pues aquí está la solución.

1.- Debes de manejar blob de tipo de dato en mysql.

Dicho esto el código quedaría:


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
private void btn_BuscarActionPerformed(java.awt.event.ActionEvent evt) {
Connection con = null;
try {
	con = getConnection();
	ps = (PreparedStatement) con.prepareStatement("SELECT * FROM dvd WHERE idDVD = ?");
	ps.setString(1, txt_Id.getText());
	rs = ps.executeQuery();
 
 
	if (!rs.next()) {
		JOptionPane.showMessageDialog(null, "No existen registros para esa clave");
	}
 
	Blob blob; //Ocupa el Blob de SQL, te sugiero que en la bd sea tipo blob
	BufferedImage buffimg = null;
	byte[] image = null;
 
 
	while (rs.next()) {
		txt_Id.setText(rs.getString("idDVD"));
		txt_Titulo.setText(rs.getString("Titulo"));
		txt_Año.setText(rs.getString("Año"));
		txt_Director.setText(rs.getString("Director"));
		txt_Discos.setText(rs.getString("Discos"));
		txt_Formato.setText(rs.getString("Formato"));
		txt_Original.setText(rs.getString("Original"));
		txt_Sinopsis.setText(rs.getString("Sinopsis"));
 
		blob=rs.getBlob("Caratula");
		image=blob.getBytes(1,(int)blob.length());
 
	//	image = rs.getBytes("Caratula");
		InputStream img = new ByteArrayInputStream(image); //Ocupa el ByteArrayInputStream para convertir el array de byte a inputstream
//		InputStream img = rs.getBinaryStream(1);
		buffimg = ImageIO.read(img);
	//	ImagenMySQL caratula = new ImagenMySQL(jpCaratula.getHeight(), jpCaratula.getWidth(), buffimg);
	//	jpCaratula.add(caratula);
	//	jpCaratula.repaint();
	}
		rs.close();
		ps.close();
		con.close();
} catch (Exception e) {
	System.err.println(e);
}


Como el tipo de dato es blob al recuperar la información tomemos la clase Blob de SQL
1
Blob blob; //Ocupa el Blob de SQL, te sugiero que en la bd sea tipo blob


Una vez recuperado convertimos en array de byte y posterior a inputstream para dejarlo a como tú lo tenias.

1
2
3
4
5
6
7
blob=rs.getBlob("Caratula");
		image=blob.getBytes(1,(int)blob.length());
		InputStream img = new ByteArrayInputStream(image); //Ocupa el ByteArrayInputStream para convertir el array de byte a inputstream
		buffimg = ImageIO.read(img);
	//	ImagenMySQL caratula = new ImagenMySQL(jpCaratula.getHeight(), jpCaratula.getWidth(), buffimg);
	//	jpCaratula.add(caratula);
	//	jpCaratula.repaint();

Nota que dejé comentado las últimas línea ya que no tengo idea de donde obtienes jpCaratula.
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
Imágen de perfil de Carlos Manuel
Val: 5
Ha aumentado su posición en 6 puestos en Java (en relación al último mes)
Gráfica de Java

Ayuda con un boton

Publicado por Carlos Manuel (2 intervenciones) el 29/04/2021 11:26:16
Muchas gracias.

Acabo de probar tu solucion y sigo estando un poco peor, ahora no me tira los datos de la base de datos, ninguno de ellos XD.

He probado cada combinacion posible sin errores en codigo, pero el campo JPanel llamado JpCaratula sigue sin mostrarme la imagen alojada en el campo Caratula de tipo BLOB de la base de datos.

Alguna idea mas?

Copio el código de toda el JForm por si sirve de orientación para algo.


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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
package Coleccion;
 
import com.mysql.jdbc.PreparedStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Blob;
import javax.swing.JOptionPane;
import java.io.File;
import Metodos.Conexion;
import Metodos.Imagen;
import Metodos.ImagenMySQL;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import static javax.management.Query.gt;
import static javax.management.Query.lt;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
 
 
public class Registro_DVD extends javax.swing.JFrame {
    public static final String URL = "jdbc:mysql://localhost:3306/peliculas_DVD";
    public static final String USERNAME = "root";
    public static final String PASSWORD = "1072Nadia.";
 
     PreparedStatement ps;
     ResultSet rs;
 
     public static Connection getConnection() {
        Connection con = null;
 
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            JOptionPane.showMessageDialog(null, "Conectado con éxito");
 
        } catch (Exception e) {
            System.out.println(e);
        }
        return con;
 
    }
    private void limpiarCajas(){
 
        txt_Id.setText(null);
        txt_Titulo.setText(null);
        txt_Año.setText(null);
        txt_Director.setText(null);
        txt_Discos.setText(null);
        txt_Formato.setText(null);
        txt_Original.setText(null);
        txt_Sinopsis.setText(null);
 
 
 
    }
 
 
    public Registro_DVD() {
        initComponents();
    }
 
    /**
     * 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">
    private void initComponents() {
 
        lblEstas = new javax.swing.JLabel();
        lblRegistro = new javax.swing.JLabel();
        lbl_ID = new javax.swing.JLabel();
        txt_Id = new javax.swing.JTextField();
        lbl_Titulo = new javax.swing.JLabel();
        txt_Titulo = new javax.swing.JTextField();
        lbl_Año = new javax.swing.JLabel();
        txt_Año = new javax.swing.JTextField();
        lbl_Director = new javax.swing.JLabel();
        txt_Director = new javax.swing.JTextField();
        lbl_Discos = new javax.swing.JLabel();
        txt_Discos = new javax.swing.JTextField();
        lbl_Formato = new javax.swing.JLabel();
        txt_Formato = new javax.swing.JTextField();
        lbl_Sinopsis = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        txt_Sinopsis = new javax.swing.JTextArea();
        btn_Guardar = new javax.swing.JButton();
        btn_Limpiar = new javax.swing.JButton();
        btn_Modificar = new javax.swing.JButton();
        btn_Eliminar = new javax.swing.JButton();
        btn_Salir = new javax.swing.JButton();
        lbl_Original = new javax.swing.JLabel();
        txt_Original = new javax.swing.JTextField();
        btn_Buscar = new javax.swing.JButton();
        jpCaratula = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
 
        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setLocation(new java.awt.Point(600, 250));
        setMaximumSize(new java.awt.Dimension(744, 500));
        setMinimumSize(new java.awt.Dimension(744, 500));
        setPreferredSize(new java.awt.Dimension(744, 500));
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
 
        lblEstas.setText("Estás en");
        getContentPane().add(lblEstas, new org.netbeans.lib.awtextra.AbsoluteConstraints(17, 6, -1, -1));
 
        lblRegistro.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N
        lblRegistro.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblRegistro.setText("REGISTRO DVD");
        getContentPane().add(lblRegistro, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 10, 250, 40));
 
        lbl_ID.setText("CODIGO ASIGNADO");
        getContentPane().add(lbl_ID, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, -1, 30));
        getContentPane().add(txt_Id, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 70, 130, -1));
 
        lbl_Titulo.setText("TITULO");
        getContentPane().add(lbl_Titulo, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 110, -1, 30));
 
        txt_Titulo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txt_TituloActionPerformed(evt);
            }
        });
        getContentPane().add(txt_Titulo, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 110, 300, -1));
 
        lbl_Año.setText("AÑO");
        getContentPane().add(lbl_Año, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 150, -1, 30));
        getContentPane().add(txt_Año, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 150, 50, -1));
 
        lbl_Director.setText("DIRECTOR");
        getContentPane().add(lbl_Director, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 180, -1, 40));
        getContentPane().add(txt_Director, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 190, 245, -1));
 
        lbl_Discos.setText("DISCOS");
        getContentPane().add(lbl_Discos, new org.netbeans.lib.awtextra.AbsoluteConstraints(80, 220, -1, 40));
        getContentPane().add(txt_Discos, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 230, 50, -1));
 
        lbl_Formato.setText("FORMATO");
        getContentPane().add(lbl_Formato, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 260, -1, 40));
        getContentPane().add(txt_Formato, new org.netbeans.lib.awtextra.AbsoluteConstraints(160, 270, 100, -1));
 
        lbl_Sinopsis.setText("SINOPSIS");
        getContentPane().add(lbl_Sinopsis, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 310, 80, 30));
 
        txt_Sinopsis.setColumns(20);
        txt_Sinopsis.setRows(5);
        jScrollPane1.setViewportView(txt_Sinopsis);
 
        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(70, 350, 420, 130));
 
        btn_Guardar.setText("GUARDAR");
        btn_Guardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_GuardarActionPerformed(evt);
            }
        });
        getContentPane().add(btn_Guardar, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 50, 90, 30));
 
        btn_Limpiar.setText("LIMPIAR");
        btn_Limpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_LimpiarActionPerformed(evt);
            }
        });
        getContentPane().add(btn_Limpiar, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 90, 90, 30));
 
        btn_Modificar.setText("MODIFICAR");
        btn_Modificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_ModificarActionPerformed(evt);
            }
        });
        getContentPane().add(btn_Modificar, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 50, 80, 30));
 
        btn_Eliminar.setText("ELIMINAR");
        btn_Eliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_EliminarActionPerformed(evt);
            }
        });
        getContentPane().add(btn_Eliminar, new org.netbeans.lib.awtextra.AbsoluteConstraints(620, 90, 80, 30));
 
        btn_Salir.setText("CERRAR");
        btn_Salir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_SalirActionPerformed(evt);
            }
        });
        getContentPane().add(btn_Salir, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 140, 110, 30));
 
        lbl_Original.setText("ORIGINAL");
        getContentPane().add(lbl_Original, new org.netbeans.lib.awtextra.AbsoluteConstraints(280, 260, -1, 40));
        getContentPane().add(txt_Original, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 270, 86, -1));
 
        btn_Buscar.setText("BUSCAR");
        btn_Buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_BuscarActionPerformed(evt);
            }
        });
        getContentPane().add(btn_Buscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 70, 90, -1));
 
        jpCaratula.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        getContentPane().add(jpCaratula, new org.netbeans.lib.awtextra.AbsoluteConstraints(510, 350, 210, 130));
 
        jLabel1.setText("CARATULA");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 320, -1, -1));
 
        pack();
    }// </editor-fold>
 
    private void btn_LimpiarActionPerformed(java.awt.event.ActionEvent evt) {
        limpiarCajas();
 
    }
 
    private void btn_GuardarActionPerformed(java.awt.event.ActionEvent evt) {
 
         if (JOptionPane.showConfirmDialog(null, "¿Estas seguro de añadir un nuevo registro?", "Aviso", JOptionPane.YES_NO_OPTION)== JOptionPane.YES_OPTION){
 
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        FileNameExtensionFilter filtro = new FileNameExtensionFilter("JPG","jpg","png","PNG","bmp","BMP");
        fc.setFileFilter(filtro);
 
        int seleccion = fc.showOpenDialog(this);
 
        PreparedStatement ps;
        ResultSet rs;
        Conexion objCon = new Conexion();
 
 
        if (seleccion ==JFileChooser.APPROVE_OPTION){
 
            File fichero = fc.getSelectedFile();
            String ruta = fichero.getAbsolutePath();
 
            try {
                FileInputStream fis = new FileInputStream(fichero);
 
                com.mysql.jdbc.Connection con = (com.mysql.jdbc.Connection) objCon.getConnection();
 
                try {
                    ps= (PreparedStatement) con.prepareStatement("INSERT INTO dvd (idDVD, Titulo, Año, Director, Discos, Formato, Original, Sinopsis, Caratula) VALUES (?,?,?,?,?,?,?,?,?)");
 
                    ps.setString(1, txt_Id.getText());
                    ps.setString(2, txt_Titulo.getText());
                    ps.setString(3, txt_Año.getText());
                    ps.setString(4, txt_Director.getText());
                    ps.setString(5, txt_Discos.getText());
                    ps.setString(6, txt_Formato.getText());
                    ps.setString(7, txt_Original.getText());
                    ps.setString(8, txt_Sinopsis.getText());
                    ps.setBinaryStream(9,fis, (int) fichero.length());
                    ps.execute();
                    JOptionPane.showMessageDialog(null, "Registro guardado con éxito.");
 
 
                }catch (SQLException ex){
                    Logger.getLogger(Registro_DVD.class.getName()).log(Level.SEVERE,null,ex);
                    JOptionPane.showMessageDialog(null, "Error al guardar Registro.");
                }
 
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Registro_DVD.class.getName()).log(Level.SEVERE, null, ex);
            }
 
            int x = jpCaratula.getWidth();
            int y = jpCaratula.getHeight();
 
            Imagen img = new Imagen(x, y, ruta);
            jpCaratula.add(img);
            jpCaratula.repaint();
        }
         }
 
        else {
           dispose();
         }
 
    }
 
    private void btn_ModificarActionPerformed(java.awt.event.ActionEvent evt) {
 
        if (JOptionPane.showConfirmDialog(null, "¿Estas seguro de modificar el registro?", "Aviso", JOptionPane.YES_NO_OPTION)== JOptionPane.YES_OPTION){
 
        JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        FileNameExtensionFilter filtro = new FileNameExtensionFilter("JPG","jpg","png","PNG","bmp","BMP");
        fc.setFileFilter(filtro);
 
        int seleccion = fc.showOpenDialog(this);
 
        PreparedStatement ps;
        ResultSet rs;
        Conexion objCon = new Conexion();
 
 
        if (seleccion ==JFileChooser.APPROVE_OPTION){
 
            File fichero = fc.getSelectedFile();
            String ruta = fichero.getAbsolutePath();
 
            try {
                FileInputStream fis = new FileInputStream(fichero);
 
                com.mysql.jdbc.Connection con = (com.mysql.jdbc.Connection) objCon.getConnection();
 
                PreparedStatement actualizar = null;
                    String query = "update dvd set "
                            + "idDVD='"+txt_Id.getText()+"', "
                            + "Titulo='"+txt_Titulo.getText()+"', "
                            + "Año='"+txt_Año.getText()+"', "
                            + "Director='"+txt_Director.getText()+"', "
                            + "Discos='"+txt_Discos.getText()+"', "
                            + "Formato='"+txt_Formato.getText()+"', "
                            + "Original='"+txt_Original.getText()+"', "
                            + "Sinopsis='"+txt_Sinopsis.getText()+"', "
                            + "Caratula='"+jpCaratula.getGraphics()+"' "
                            + "where idDVD='"+txt_Id.getText()+"';";
                try {
 
                    actualizar=(PreparedStatement) con.prepareStatement(query);
                    actualizar.executeUpdate();
 
                    int x = jpCaratula.getWidth();
                    int y = jpCaratula.getHeight();
 
                    Imagen img = new Imagen(x, y, ruta);
                    jpCaratula.add(img);
                    jpCaratula.repaint();
 
                    JOptionPane.showMessageDialog(null, "Registro actualizado con éxito.");
 
 
                }catch (SQLException ex){
                    Logger.getLogger(Registro_DVD.class.getName()).log(Level.SEVERE,null,ex);
                    JOptionPane.showMessageDialog(null, "Error al actualizar el registro.");
                }
 
            } catch (FileNotFoundException ex) {
                Logger.getLogger(Registro_DVD.class.getName()).log(Level.SEVERE, null, ex);
            }
 
            }
         }
 
        else {
           dispose();
 
        }
 
    }
 
    private void btn_EliminarActionPerformed(java.awt.event.ActionEvent evt) {
 
        if (JOptionPane.showConfirmDialog(null, "¿Estas seguro de eliminar el registro?", "Aviso", JOptionPane.YES_NO_OPTION)== JOptionPane.YES_OPTION){
 
        Connection con = null;
 
        try{
 
            con = getConnection();
            ps = (PreparedStatement) con.prepareStatement("DELETE FROM peliculas_dvd.dvd WHERE idDVD=?");
            ps.setInt(1, Integer.parseInt(txt_Id.getText()));
 
            int res = ps.executeUpdate();
 
            if(res > 0){
                JOptionPane.showMessageDialog(null, "Registro eliminado con éxito.");
                limpiarCajas();
 
            } else {
                JOptionPane.showMessageDialog(null, "Error al eliminar registro\nInténtelo de nuevo.");
                limpiarCajas();
            }
 
            con.close();
 
 
        }catch(Exception e){
            System.err.println(e);
        }
 
        } else {
           dispose();
        }
 
    }
 
    private void btn_SalirActionPerformed(java.awt.event.ActionEvent evt) {
        dispose();
    }
 
    private void btn_BuscarActionPerformed(java.awt.event.ActionEvent evt) {
 
        Connection con = null;
 
 
        try {
            con = getConnection();
            ps = (PreparedStatement) con.prepareStatement("SELECT * FROM dvd WHERE idDVD = ?");
            ps.setString(1, txt_Id.getText());
            rs = ps.executeQuery();
 
 
            Blob blob; //Ocupa el Blob de SQL, te sugiero que en la bd sea tipo blob
            BufferedImage buffimg = null;
            byte[] image = null;
 
            if (!rs.next()) {
            JOptionPane.showMessageDialog(null, "No existen registros para esa clave");
            }
 
            while (rs.next()) {
                txt_Id.setText(rs.getString("idDVD"));
                txt_Titulo.setText(rs.getString("Titulo"));
                txt_Año.setText(rs.getString("Año"));
                txt_Director.setText(rs.getString("Director"));
                txt_Discos.setText(rs.getString("Discos"));
                txt_Formato.setText(rs.getString("Formato"));
                txt_Original.setText(rs.getString("Original"));
                txt_Sinopsis.setText(rs.getString("Sinopsis"));
 
                blob = rs.getBlob("Caratula");
                image = blob.getBytes(1, (int) blob.length());
 
                image = rs.getBytes("Caratula");
                InputStream img = new ByteArrayInputStream(image); //Ocupa el ByteArrayInputStream para convertir el array de byte a inputstream
                //InputStream img = rs.getBinaryStream(1);
                buffimg = ImageIO.read(img);
                	ImagenMySQL caratula = new ImagenMySQL(jpCaratula.getHeight(), jpCaratula.getWidth(), buffimg);
                	jpCaratula.add(caratula);
                	jpCaratula.repaint();
            }
 
            rs.close();
            ps.close();
            con.close();
} catch (Exception e) {
	System.err.println(e);
}
 
 
    }
 
    private void txt_TituloActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }
 
 
 
 
    /**
     * @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(Registro_DVD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Registro_DVD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Registro_DVD.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Registro_DVD.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 Registro_DVD().setVisible(true);
            }
        });
    }
 
    // Variables declaration - do not modify
    private javax.swing.JButton btn_Buscar;
    private javax.swing.JButton btn_Eliminar;
    private javax.swing.JButton btn_Guardar;
    private javax.swing.JButton btn_Limpiar;
    private javax.swing.JButton btn_Modificar;
    private javax.swing.JButton btn_Salir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel jpCaratula;
    private javax.swing.JLabel lblEstas;
    private javax.swing.JLabel lblRegistro;
    private javax.swing.JLabel lbl_Año;
    private javax.swing.JLabel lbl_Director;
    private javax.swing.JLabel lbl_Discos;
    private javax.swing.JLabel lbl_Formato;
    private javax.swing.JLabel lbl_ID;
    private javax.swing.JLabel lbl_Original;
    private javax.swing.JLabel lbl_Sinopsis;
    private javax.swing.JLabel lbl_Titulo;
    private javax.swing.JTextField txt_Año;
    private javax.swing.JTextField txt_Director;
    private javax.swing.JTextField txt_Discos;
    private javax.swing.JTextField txt_Formato;
    private javax.swing.JTextField txt_Id;
    private javax.swing.JTextField txt_Original;
    private javax.swing.JTextArea txt_Sinopsis;
    private javax.swing.JTextField txt_Titulo;
    // End of variables declaration
}
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