Ayuda JCombobox Java Swing

Chiva_3

Bovino maduro
#1
Que tal, quería ver si me pueden ayudar con este problema, resulta que estoy obteniendo datos de una base de datos sobre unas cuentas y quiero ponerlas en un Combobox para seleccionar una opción, para añadirlas al Combobox primero uso el removeallItems() para quitar las anteriores opciones y despues voy añadiendo una a una las opciones, el problema viene con el removeAllItems() que me tira un NullPointeException. ¿Alguien sabe porque?
Aqui dejo mi código:
Código:
private void jLNombresValueChanged(javax.swing.event.ListSelectionEvent evt) {                                        
    try { 
        if( jLNombres.getSelectedIndex() == -1 ) 
            return; 
        cliente = new CCliente(); 
        int id = controlador.IDCliente( jLNombres.getSelectedValue().toString() ); 
        cliente = controlador.consultaCliente( id ); 
        Iterator iterator = cliente.getCuentas().iterator(); 
        CCuenta nueva = new CCuenta(); 
        String nombre; 
        
        jCCuentas.removeAllItems();  //Aqui es el problema 
        
        while( iterator.hasNext() ) 
        { 
            nueva = ( CCuenta )iterator.next(); 
            nombre = nueva.getCuenta(); 
            jCCuentas.addItem(nombre); 
        } 
    } catch (Exception e) { 
        JOptionPane.showMessageDialog( this , "Se presentó el siguiente error: " + e.getMessage() , "Error" , JOptionPane.ERROR_MESSAGE ); 
    } 
}                                      

private void jCCuentasActionPerformed(java.awt.event.ActionEvent evt) {                                          
    try { 
        String cuenta = jCCuentas.getSelectedItem().toString(); 
        this.cuenta = new CCuenta(); 
        this.cuenta = controlador.consultaCuenta(cuenta); 
        lSaldo.setText( "Saldo: " + this.cuenta.estado() ); 
    } catch (Exception e) { 
        JOptionPane.showMessageDialog( this , "Se presentó el siguiente error: " + e.getMessage() , "Error" , JOptionPane.ERROR_MESSAGE ); 
    } 
}
:mota:

Gracias de antemano
 

tochoromero

Bovino adicto
#2
Si lo que quieres borrar todo lo que tiene lo que puedes hacer es volver a inicializar el objeto por ejemplo si combobox se llama cbAlgo, cuando quieras borrar su continido haz cbAlgo = new JComboBox();
Eso debe de borrar lo que tenía antes.
 
#3
Creo que el error te está indicando que tu jCCuentas no se ha instanciado. Comenta la línea del problema, y si el error aparece de nuevo en la línea de jCCuentas.addItem(nombre), significa que tu combo necesita un JComboBox jCCuentas = new JComboBox() antes de poder invocar sus métodos.
 

Chiva_3

Bovino maduro
#4
Respuesta

Gracias por haber respondido, ahora mismo acabo de responderme solo XD, dejo aquí la solución por si a alguien le llega a pasar lo mismo, porque mientras googleaba encontre mi pregunta XD.

Mi código quedo así al final

Código:
private void jLNombresValueChanged(javax.swing.event.ListSelectionEvent evt) {//GEN-FIRST:event_jLNombresValueChanged 
    try { 
        if( jLNombres.getSelectedIndex() == -1 ) 
            return; 
        cliente = new CCliente(); 
        int id = controlador.IDCliente( jLNombres.getSelectedValue().toString() ); 
        cliente = controlador.consultaCliente( id ); 

        int t = cliente.getCuentas().size(); 
        String nombre[] = new String[t]; 
        int j = 0; 
        for( CCuenta i : cliente.getCuentas() ) 
        { 
            nombre[j] = i.getCuenta(); 
            j++; 
        } 

        jCCuentas.setModel( new DefaultComboBoxModel( nombre ) ); 
        jCCuentas.setSelectedIndex(0); 
//        jCCuentas.removeAllItems(); 
// 
//        while( iterator.hasNext() ) 
//        { 
//            nueva = ( CCuenta )iterator.next(); 
//            nombre = nueva.getCuenta(); 
//            jCCuentas.addItem(nombre); 
//        } 
    } catch (Exception e) { 
        JOptionPane.showMessageDialog( this , "Se presentó el siguiente error: " + e.getMessage() , "Error" , JOptionPane.ERROR_MESSAGE ); 
    } 
}//GEN-LAST:event_jLNombresValueChanged 

private void jCCuentasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCCuentasActionPerformed 
    try { 
        String cuenta = jCCuentas.getSelectedItem().toString(); 
        this.cuenta = new CCuenta(); 
        this.cuenta = controlador.consultaCuenta(cuenta); 
        lSaldo.setText( "Saldo: " + this.cuenta.estado() ); 
    } catch (Exception e) { 
        JOptionPane.showMessageDialog( this , "Se presentó el siguiente error: " + e.getMessage() , "Error" , JOptionPane.ERROR_MESSAGE ); 
    } 
}//GEN-LAST:event_jCCuentasActionPerformed
Las líneas claves son las siguientes:

Código:
        int t = cliente.getCuentas().size(); 
        String nombre[] = new String[t]; 
        int j = 0; 
        for( CCuenta i : cliente.getCuentas() ) 
        { 
            nombre[j] = i.getCuenta(); 
            j++; 
        } 

        jCCuentas.setModel( new DefaultComboBoxModel( nombre ) ); 
        jCCuentas.setSelectedIndex(0);
En vez de eliminar los items con deleteallitems() y despues irlos agregando uno a uno es mejor poner el modelo del ComboBox y que se haga bolas el solo
La verdad no tengo idea de porqué no funcionaba el anterior, según leí puede ser porqué tiene conflictos con el ActionPerformed, en fin, de esta manera me funciona perfecto.

Así termine mi proyecto al fin :cucu:

Saludos
 
Arriba