my problem is the following, I have a jtable
loaded from the DB and I want to select a row, by pressing enter I am charged a JCombobox
that I have in another JFrame
which I do:
Event pressing enter
if ((evt.getKeyCode() == KeyEvent.VK_ENTER)) {
int filaSelecionada = jTablaLocalidades.getSelectedRow();
if (filaSelecionada == -1) {
JOptionPane.showMessageDialog(null, "No se selecciono ninguna fila");
}else{
Localidad localidad = new Localidad();
localidad.setNombre(jTablaLocalidades.getValueAt(filaSelecionada, 1).toString());
this.agregarCliente.jcboLocalidad.getModel().setSelectedItem(localidad.getNombre());
agregarCliente.setVisible(true);
this.dispose();
}
}
The combo is filled with the object that I select from the row but it does not save me, I get it
java.lang.ClassCastException: java.lang.String cannot be cast to Datos.Localidad
By pressing the save button, which brings me to the line
Localidad cboLocalidad = (Localidad)jcboLocalidad.getSelectedItem();
If I change to this.agregarCliente.jcboLocalidad.getModel().setSelectedItem(localidad);
saves me but does not save me the id in my BD, it saves me 0 in my table of the BD I explain myself? What I need is to save the object with the id of that selected location.
My Locality class
private int idlocalidad;
private String nombre;
private int codpostal;
private String DDN;
private int idprovincia;
private int idzona;
public Localidad() {
}
public Localidad(int idlocalidad, String nombre) {
this.idlocalidad = idlocalidad;
this.nombre = nombre;
}
public int getIdlocalidad() {
return idlocalidad;
}
public void setIdlocalidad(int idlocalidad) {
this.idlocalidad = idlocalidad;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public int getCodpostal() {
return codpostal;
}
public void setCodpostal(int codpostal) {
this.codpostal = codpostal;
}
public String getDDN() {
return DDN;
}
public void setDDN(String DDN) {
this.DDN = DDN;
}
public int getIdprovincia() {
return idprovincia;
}
public void setIdprovincia(int idprovincia) {
this.idprovincia = idprovincia;
}
public int getIdzona() {
return idzona;
}
public void setIdzona(int idzona) {
this.idzona = idzona;
}
@Override
public String toString() {
return nombre;
}
I charge the combo as follows:
private void cboLocalidad(){
DefaultComboBoxModel modelo = new DefaultComboBoxModel();
try {
Connection miComando = AdministradorConfiguracion.obtenerComandoMySql();
CallableStatement obtenerLocalidades = miComando.prepareCall("call obtener_localidades()");
ResultSet rs = obtenerLocalidades.executeQuery();
while (rs.next()) {
modelo.addElement(new Localidad(rs.getInt("Nro"), rs.getString("Localidad")));
jcboLocalidad.setModel(modelo);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Error al cargar combo:\n"
+ e, "Error en la operación", JOptionPane.ERROR_MESSAGE);
}
}
Any idea what I'm doing wrong? Thanks again.