Java - Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

 
Vista:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException

Publicado por ANAHI (2 intervenciones) el 28/06/2019 08:16:18
Hola, estoy tratando de generar consultas y modificaciones en netbeans conectado con mysql la conexion se encuentra bien hecha y a la vista no hay errores pero cuando le doy run me sale este error, no se como solucionarlo por favor si alguien me podria ayudar!
Gracias

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
public final class Producto extends javax.swing.JFrame {
 
    Connection con;
    Statement stmt;
    String var,var2;
     public Producto() {
        initComponents();
        limpi();
        bloq();
        mostrar();
         this.setTitle("PRODUCTOS");
        this.setLocation(100,55);
        this.setResizable(false);
        ImageIcon icono = new ImageIcon("C:\\Users\\hp\\Documents\\NetBeansProjects\\s_heladeria\\src\\imagenes\\co.jpg");
        this.setIconImage(icono.getImage());
 
    }
 
     void limpi(){
        id.setText("");
        tp.setText("");
        pr.setText("");
        tam.setText("");
        cant.setText("");
        mar.setText("");
        des.setText("");
        fe.setText("DD-MM-AAAA");
        fi.setText("DD-MM-AAAA");
        bus.setText("");
 
    }
 
    void bloq(){
        id.setEnabled(false);
        tp.setEnabled(false);
        pr.setEnabled(false);
        tam.setEnabled(false);
        cant.setEnabled(false);
        mar.setEnabled(false);
        des.setEnabled(false);
        fe.setEnabled(false);
        fi.setEnabled(false);
        nuevo.setEnabled(true);
        guardar.setEnabled(true);
    }
 
    void desbloquear(){
        id.setEnabled(true);
        tp.setEnabled(true);
        pr.setEnabled(true);
        tam.setEnabled(true);
        cant.setEnabled(true);
        mar.setEnabled(true);
        des.setEnabled(true);
        fe.setEnabled(true);
        fi.setEnabled(true);
        nuevo.setEnabled(false);
        guardar.setEnabled(true);
    }
 
    void mostrar(){
    DefaultTableModel modelo = new DefaultTableModel();
    modelo.addColumn("CODIGO");
    modelo.addColumn("TIPO");
    modelo.addColumn("DESCRIPCION");
    modelo.addColumn("PRECIO");
    modelo.addColumn("TAMAÑO");
    modelo.addColumn("CANTIDAD");
    modelo.addColumn("MARCA");
    modelo.addColumn("FECHA EXPIRACION");
    modelo.addColumn("FECHA INGRESO");
    produc.setModel(modelo);
 
    String sql ="SELECT * FROM producto";
 
    String datos[] = new String [9];
    Statement st;
        try {
            st = con.createStatement();
            ResultSet rs = st.executeQuery(sql);
            while(rs.next()){
 
            datos[0] = rs.getString(2);
            datos[1] = rs.getString(3);
            datos[2] = rs.getString(4);
            datos[3] = rs.getString(5);
            datos[4] = rs.getString(6);
            datos[6] = rs.getString(7);
            datos[7] = rs.getString(8);
            datos[8] = rs.getString(9);
            modelo.addColumn(datos);
 
            }
 
            produc.setModel(modelo);
 
        } catch (SQLException ex) {
            Logger.getLogger(Producto.class.getName()).log(Level.SEVERE, null, ex);
        }
 
 
 
    }
 
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
    private void initComponents() {
 
 
 
        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
 
        jPanel1.setBackground(new java.awt.Color(0, 206, 206));
 
        jLabel1.setFont(new java.awt.Font("Times New Roman", 0, 36)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 204, 255));
        jLabel1.setText("PRODUCTOS");
 
        jLabel2.setText("CODIGO");
 
        jLabel3.setText("TIPO");
 
        fi.setText("DD-MM-AAAA");
        fi.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                fiActionPerformed(evt);
            }
        });
 
        jLabel4.setText("PRECIO");
 
        jLabel5.setText("TAMAÑO");
 
        jLabel6.setText("CANTIDAD");
 
        jLabel7.setText("DESCRPCION");
 
        jLabel8.setText("FECHA DE EXPIRACION");
 
        fe.setText("DD-MM-AAAA");
 
        jLabel9.setText("MARCA");
 
        jLabel10.setText("FECHA DE INGRESO");
 
        nuevo.setText("NUEVO");
        nuevo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nuevoActionPerformed(evt);
            }
        });
 
        guardar.setText("GUARDAR");
        guardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                guardarActionPerformed(evt);
            }
        });
 
        atras.setText("ATRAS");
        atras.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                atrasActionPerformed(evt);
            }
        });
 
        salir.setText("SALIR");
        salir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                salirActionPerformed(evt);
            }
        });
 
        buscar.setText("BUSCAR");
        buscar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buscarActionPerformed(evt);
            }
        });
 
        produc.setBackground(new java.awt.Color(0, 204, 204));
        produc.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        produc.setForeground(new java.awt.Color(255, 255, 255));
        produc.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
 
            },
            new String [] {
 
            }
        ));
        jScrollPane1.setViewportView(produc);
 
        mod.setText("MODIFICAR");
        mod.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                modActionPerformed(evt);
            }
        });
 
        act.setText("ACTUALIZAR");
        act.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                actActionPerformed(evt);
            }
        });
 
        elim.setText("ELIMINAR");
        elim.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                elimActionPerformed(evt);
            }
        });
 
        pack();
    }// </editor-fold>
public void consulta() {
        desbloquear();
        String cap="";
        ResultSet rs = null;
        var2 = var;
        String sql2="Select * FROM producto where Codigo_producto = '"+var2+"'";
 
   try {
 
                  String url = "jdbc:mysql://localhost:3306/heladeria_inventario";
                  String usuario = "root";
                  String contraseña = "youandi123";
 
     Class.forName("com.mysql.jdbc.Driver").newInstance();
 
 
     con = DriverManager.getConnection(url,usuario,contraseña);
 
     if ( con != null )
	   System.out.println("Se ha establecido una conexión a la base de datos " +
	                                       "\n " + url );
 
	stmt = con.createStatement();
	rs = stmt.executeQuery(sql2);
 
	int i=1;
	   while ( rs.next() ) {
 
	           String cod = rs.getString("Codigo_producto");
	           String tip = rs.getString("tipo");
	           String dess = rs.getString("Decripcion");
                   String pre = rs.getString("precio");
                   String tama = rs.getString("Tamaño");
                   String canti = rs.getString("cantidad");
                   String marc = rs.getString("Marca");
                   String fex = rs.getString("fe");
                   String fin = rs.getString("fi");
	           System.out.println("Sitio Web "+ (i++) + ":\n"
 
                           + cod + "\n"
                           + tip + "\n"
                           + dess + "\n"
                           + pre + "\n"
	                   + tama + "\n"
                           + canti + "\n"
                           + marc + "\n"
                           + fex + "\n"
                           + fin + "\n\n" );
 
                     id.setText(cod);
                     tp.setText(tip);
                     des.setText(dess);
                     pr.setText(pre);
                     tam.setText(tama);
                     cant.setText(canti);
                     mar.setText(marc);
                     fe.setText(fex);
                     fi.setText(fin);
 
	         }
	        }
                  catch( SQLException ex ) {
                      ex.printStackTrace();
	                  } catch (InstantiationException ex) {
            Logger.getLogger(Producto.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            Logger.getLogger(Producto.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Producto.class.getName()).log(Level.SEVERE, null, ex);
        }
 
	              finally {
	                  if ( rs != null ) {
	                      try    {
	                          rs.close();
	                      } catch( SQLException ex ) {
	                          System.out.println( ex.getMessage());
	                          ex.printStackTrace();
	                      }
	                  }
	                  if ( stmt != null ) {
	                      try    {
	                          stmt.close();
	                      } catch( SQLException ex ) {
	                          System.out.println( ex.getMessage());
	                          ex.printStackTrace();
	                      }
	                  }
	                  if ( con != null ) {
	                      try    {
	                          con.close();
	                      } catch( SQLException ex ) {
	                          System.out.println( ex.getMessage());
	                          ex.printStackTrace();
         }
       }
     }
    }
    private void fiActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }
 
    private void nuevoActionPerformed(java.awt.event.ActionEvent evt) {
         desbloquear();
        id.requestFocus();
    }
 
    private void salirActionPerformed(java.awt.event.ActionEvent evt) {
        this.dispose();
    }
 
    private void atrasActionPerformed(java.awt.event.ActionEvent evt) {
         frmbienvenido f= new frmbienvenido();
     f.setVisible(true);
     dispose();
    }
 
    private void guardarActionPerformed(java.awt.event.ActionEvent evt) {
       String cadena2,cadena3,cadena4,cadena5,cadena6,cadena7,cadena8,cadena9,cadena10;
 
        cadena2 = id.getText();
        cadena3 = tp.getText();
        cadena4 = des.getText();
        cadena5 = pr.getText();
        cadena6 = tam.getText();
        cadena7 = cant.getText();
        cadena8 = mar.getText();
        cadena9 = fe.getText();
        cadena10 = fi.getText();
 
 
        if ((pr.getText().equals("")) || (tp.getText().equals("")) || (pr.getText().equals("")) || (tam.getText().equals(""))
           || (mar.getText().equals("")) || (cant.getText().equals("")) || (des.getText().equals("")) || (fe.getText().equals(""))
           || (fi.getText().equals(""))) {
 
            javax.swing.JOptionPane.showMessageDialog(this,"Debe llenar todos los campos \n","AVISO!",javax.swing.JOptionPane.INFORMATION_MESSAGE);
            tp.requestFocus();
        }
 
 
        else {
        try {
 
            String url = "jdbc:mysql://localhost:3306/heladeria_inventario";
            String usuario = "root";
            String contraseña = "youandi123";
 
             Class.forName("com.mysql.jdbc.Driver").newInstance();
             con = DriverManager.getConnection(url,usuario,contraseña);
             if ( con != null )
                    System.out.println("Se ha establecido una conexión a la base de datos " +
                                       "\n " + url );
 
                  stmt = con.createStatement();
                  stmt.executeUpdate("INSERT INTO producto VALUES('"+cadena2+"','"+cadena3+"','"+cadena4+"','"+cadena5+"','"+cadena6+"','"+cadena7+"','"+cadena8+"','"+cadena9+"','"+cadena10+"')");
                  System.out.println("Los valores han sido agregados a la base de datos ");
 
 
        } catch (InstantiationException ex) {
           Logger.getLogger(Producto.class.getName()).log(Level.SEVERE, null, ex);
       } catch (IllegalAccessException ex) {
           Logger.getLogger(Producto.class.getName()).log(Level.SEVERE, null, ex);
       } catch (ClassNotFoundException ex) {
           Logger.getLogger(Producto.class.getName()).log(Level.SEVERE, null, ex);
       } catch (SQLException ex) {
           Logger.getLogger(Producto.class.getName()).log(Level.SEVERE, null, ex);
       }
 
        finally {
            if (con != null) {
                try {
                    con.close();
                    stmt.close();
                } catch ( SQLException e ) {
                         System.out.println( e.getMessage());
                }
            }
        }
         javax.swing.JOptionPane.showMessageDialog(this,"Registro exitoso! \n","AVISO!",javax.swing.JOptionPane.INFORMATION_MESSAGE);
        }
        limpi();
    }
 
    private void buscarActionPerformed(java.awt.event.ActionEvent evt) {
         String cap="";
        ResultSet rs = null;
        var = javax.swing.JOptionPane.showInputDialog(this,"Codigo del producto","BUSCAR",javax.swing.JOptionPane.QUESTION_MESSAGE);
        String sql="SELECT* FROM  producto WHERE Codigo_producto = '"+var+"'";
        if(var == null)
        javax.swing.JOptionPane.showMessageDialog(this,"La accion fue cancelada","AVISO!",javax.swing.JOptionPane.INFORMATION_MESSAGE);
        else {
            if (var.equals("")) {
                javax.swing.JOptionPane.showMessageDialog(this,"Favor de ingresar el codigo del \n del productoque desea consultar","AVISO!",javax.swing.JOptionPane.INFORMATION_MESSAGE);
            }
            else {
                try {
 
                    String url = "jdbc:mysql://localhost:3306/heladeria_inventario";
                    String usuario = "root";
                    String contraseña = "youandi123";
 
                    Class.forName("com.mysql.jdbc.Driver").newInstance();
                    con = DriverManager.getConnection(url,usuario,contraseña);
                    if ( con != null )
                    System.out.println("Se ha establecido una conexión a la base de datos " +
                        "\n " + url );
 
                    stmt = con.createStatement();
                    rs = stmt.executeQuery(sql);
 
                    while(rs.next()) {
 
                        cap = rs.getString("tipo");
 
                        if (cap.equals("aderezo") || cap.equals("cono") || cap.equals("elaboracion") ) {
 
                            consulta();
                        }
                    }   // fin del bucle While
 
                } catch (InstantiationException | IllegalAccessException | ClassNotFoundException | SQLException ex) {
                    Logger.getLogger(Producto.class.getName()).log(Level.SEVERE, null, ex);
                }
 
                finally {
                    if (con != null) {
                        try {
                            con.close();
                            stmt.close();
                        } catch ( Exception e ) {
                            System.out.println( e.getMessage());
                        }
                    }
                }
                if (!cap.equals("aderezo") && !cap.equals("cono") && !cap.equals("elaboracion")) {
                    javax.swing.JOptionPane.showMessageDialog(this,"El usuario no fue encontrado\n","ERROR!", javax.swing.JOptionPane.ERROR_MESSAGE);
 
                }
            }
        }
 
 
    }
 
    private void modActionPerformed(java.awt.event.ActionEvent evt) {
       int fila = produc.getSelectedRow();
       if(fila>=0){
          bus.setText(produc.getValueAt(fila, 0).toString());
          id.setText(produc.getValueAt(fila, 1).toString());
          tp.setText(produc.getValueAt(fila, 2).toString());
          des.setText(produc.getValueAt(fila, 3).toString());
          pr.setText(produc.getValueAt(fila, 4).toString());
          tam.setText(produc.getValueAt(fila, 5).toString());
          cant.setText(produc.getValueAt(fila, 6).toString());
          mar.setText(produc.getValueAt(fila, 7).toString());
          fe.setText(produc.getValueAt(fila, 8).toString());
          fi.setText(produc.getValueAt(fila, 9).toString());
       }
       else {
       JOptionPane.showMessageDialog(null, "Fila no seleccionada");
       }
    }
 
    private void actActionPerformed(java.awt.event.ActionEvent evt) {
        try {
            PreparedStatement pps;
            pps = con.prepareStatement("UPDATE producto SET Codigo_producto='"+id.getText()+"', tipo='"+tp.getText()+"', Decripcion='"+des.getText()+"', precio='"+pr.getText()+"', Tamaño='"+tam.getText()+"', cantidad='"+cant.getText()+"', Marca='"
                    +mar.getText()+"', fe='"+fe.getText()+"', fi='"+fi.getText()+"' WHERE Codigo_producto ='"+bus.getText()+"'" );
             pps.executeUpdate();
             JOptionPane.showMessageDialog(null, "Datos actualizados");
             limpi();
             mostrar();
        } catch (SQLException ex) {
            Logger.getLogger(Producto.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
 
    private void elimActionPerformed(java.awt.event.ActionEvent evt) {
          int fila=produc.getSelectedRow();
       String valor = produc.getValueAt(fila, 0).toString();
       if(fila>=0){
           try {
               PreparedStatement pps = con.prepareStatement("DELETE FROM producto WHERE Codigo_producto='"+valor+"'");
          JOptionPane.showMessageDialog(null, "Dato eliminado");
           } catch (SQLException ex) {
               Logger.getLogger(Producto.class.getName()).log(Level.SEVERE, null, ex);
           }
       }
    }

ERROR
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at clases.Producto.mostrar(Producto.java:94)
at clases.Producto.<init>(Producto.java:25)
at clases.Producto.lambda$main$0(Producto.java:729)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
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