java.lang.ClassCastException: java.lang.String can not be cast to Data.Locality

1

My question is this, how can I store the identifier and the name of the locality at the time of auto completion of a JComboBox? Because when I filter inside the combo, I want to store the selected element but I get an error.

java.lang.ClassCastException: java.lang.String cannot be cast to Datos.Localidad

The following code shows the line where you exit the exception between ///.

private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {                                           
        if (!txtNombre.getText().isEmpty()) {
            if (!txtApellido.getText().isEmpty()) {
                if (cboLocalidad.getSelectedItem() != null) {
                    cliente.setNombre(txtNombre.getText());
                    cliente.setApellido(txtApellido.getText());
                    cliente.setTelefono(txtTelefono.getText());
                    cliente.setDomicilio(txtDomicilio.getText());
                    cliente.setFacebook(txtFacebook.getText());
                    ////////////////////////////////
                    Localidad cbo = (Localidad) cboLocalidad.getSelectedItem();
                    int id = cbo.getIdlocalidad();
                    ///////////////////////////////
                    cliente.setIdlocalidad(id);
                    cliente.guardar();
                    dispose();
                } else {
                    JOptionPane.showMessageDialog(null, "Debe seleccionaar una Localidad.", "Advertencia", JOptionPane.WARNING_MESSAGE);
                    cboLocalidad.requestFocus();
                }
            } else {
                JOptionPane.showMessageDialog(null, "Debe ingresar un Apellido.", "Advertencia", JOptionPane.WARNING_MESSAGE);
                txtApellido.requestFocus();
            }
        } else {
            JOptionPane.showMessageDialog(null, "Debe ingresar un Nombre.", "Advertencia", JOptionPane.WARNING_MESSAGE);
            txtNombre.requestFocus();
        }
    } 

That line of code is necessary to capture the id selected when selecting an item in the JComboBox and then store it in my BD. The locality class is the following:

public class Localidad{
    public int idlocalidad;
    public String localidad;

    public Localidad(int idlocalidad, String localidad) {
        this.idlocalidad = idlocalidad;
        this.localidad = localidad;
    }
    ////////////////////////////////////////////////////
    public int getIdlocalidad() {
        return idlocalidad;
    }

    public void setIdlocalidad(int idlocalidad) {
        this.idlocalidad = idlocalidad;
    }

    public String getLocalidad() {
        return localidad;
    }

    public void setLocalidad(String localidad) {
        this.localidad = localidad;
    }

    @Override
    public String toString(){
        return localidad;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) {
            return false;
        }
        if (this == obj) {
            return true;
        }
        if (!(obj instanceof Localidad)) {
            return false;
        }
        Localidad localidad = (Localidad) obj;
        if (idlocalidad != localidad.idlocalidad) {
            return false;
        }
        if (this.localidad != null ? !this.localidad.equals(localidad.localidad) : localidad.localidad != null) {
            return false;
        }
        return true;
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 89 * hash + (this.localidad != null ? this.localidad.hashCode() : 0);
        hash = 89 * hash + this.idlocalidad;
        return hash;
    }


}

The JComboBox is filled in the following way.

private DefaultComboBoxModel comboLocalidad() {
        DefaultComboBoxModel valor = new DefaultComboBoxModel();
        try {
            Connection miComando = AdministradorConfiguracion.obtenerComandoMySql();
            CallableStatement obtenerLocalidades = miComando.prepareCall("call obtener_localidades()");
            ResultSet rs = obtenerLocalidades.executeQuery();
            while (rs.next()) {
                cboLocalidad.setModel(valor);
                valor.addElement(new Localidad(rs.getInt("Nro"), rs.getString("Localidad")));
                //Se instancia la clase y se le pasa al constructor los datos cargados en el "rs".
                Localidad cbo = new Localidad(rs.getInt("Nro"), rs.getString("Localidad"));
                //Se establece el elemento que se quiera que esté seleccionado por defecto.
                cbo.idlocalidad = 0;
                cbo.localidad = "";
                cboLocalidad.setSelectedItem(cbo);
            }
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error al intentar auto completar busqueda:\n"
                    + e, "Error en la operación", JOptionPane.ERROR_MESSAGE);
        }
        return valor;
    }

I perform a method which is used to find a location within the editable jcombobox.

private void autoCompletarLocalidad(String cadBus) {

        List<String> filterArray = new ArrayList<String>();
        String cadena = "";
        try {
            Connection miComando = AdministradorConfiguracion.obtenerComandoMySql();
            CallableStatement obtenerLocalidades = miComando.prepareCall("call obtener_localidades_por_cadena(?)");
            obtenerLocalidades.setString(1, cadBus);
            ResultSet rs = obtenerLocalidades.executeQuery();
            while (rs.next()) {
                cadena = rs.getString("Localidad");
                filterArray.add(cadena);
            }

        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "Error al intentar auto completar busqueda:\n"
                    + e, "Error en la operación", JOptionPane.ERROR_MESSAGE);
        }

        if (filterArray.size() > 0) {
            cboLocalidad.setModel(new DefaultComboBoxModel(filterArray.toArray()));
            cboLocalidad.setSelectedItem(cadBus);
            cboLocalidad.showPopup();
        } else {
            cboLocalidad.hidePopup();
        }
    }

I make a method that invokes the keyReleased () method while writing it, it goes auto filling the jcombobox.

private void cboAutoComplete() {
        final JTextField textoBuscado = (JTextField) cboLocalidad.getEditor().getEditorComponent();
        textoBuscado.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent ke) {
                SwingUtilities.invokeLater(new Runnable() {
                    @Override
                    public void run() {
                        autoCompletarLocalidad(textoBuscado.getText());
                    }
                });
            }
        });
    }

Then I call them from the constructor.

public AgregarClientes() {
        initComponents();
        comboLocalidad();
        cboAutoComplete();
    }

Until then everything is ok, the problem arises when looking for a location within the jcombobox, it tells me java.lang.ClassCastException: java.lang.String cannot be cast to Datos.Localidad when passing the string and selecting it, when I click save, that exception comes out. Excite some other way to store the ID of the searched string? I hope to see it clear. Thanks again.

    
asked by Gerardo Ferreyra 01.05.2017 в 23:09
source

1 answer

1

Let's see ...

The basis of the problem is that in your autocomplete method, in the comboBox what you save is only String ; when autocompleta you do:

List<String> filterArray = new ArrayList<String>();
... // añadir las strings que cumplen el filtro
cboLocalidad.setModel(new DefaultComboBoxModel(filterArray.toArray()));

Obviously, if you have saved String returns String , and you can not convert a String to another class.

What you have to do is what you already do well when you originally fill in the comboBox ... make the model work with Localidad and fill the list with instances of that class.

valor.addElement(new Localidad(rs.getInt("Nro"), rs.getString("Localidad")));
cboLocalidad.setModel(valor);

Notes:

  • As A. Cedano comments, it would be nice to get used to using generics everywhere ( DefaultComboBoxModel<Localidad> valor = new DefaultComboBoxModel<Localidad>(); )

  • In comboLocalidad() , you assign the model to each iteration of the result reading. It is enough that you do it after leaving the loop. Same as the setSelectedItem() .

  • With the setSelectedItem() , if what you want is that there is no item selected, just make setSelectedItem(null) . And if the model is newly created, not even that.

  • answered by 02.05.2017 / 01:13
    source