I have a jcombobox that loads the regions of Chile, I use a class called Regions to also save the ID. I need to consult the data of a person to load the jcombobox (which does it without problems), but I also need to select the region of the person. I can not simply use a .setSelectedItem ("Region-name") because the combobox only receives objects from the Regions class.
The class code is this:
public class Regiones {
public int id;
public String nombre, num_r;
Connection connect;
public Regiones(int id, String nombre) {
this.id = id;
this.nombre = nombre;
}
public Regiones() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNum_r() {
return num_r;
}
public void setNum_r(Integer id) {
this.num_r = num_r;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public void cargarR(JComboBox<Regiones> cbx_region){
connect = Conexion.getConnection();
String sql = "SELECT * FROM region WHERE ACTIVO_REGION = 'SI';";
ResultSet rs = null;
PreparedStatement ps = null;
try {
ps = connect.prepareStatement(sql);
rs = ps.executeQuery();
for (int i=0; i<=1; i++){
if (i == 0){
int a = 0; String b ="", c ="Seleccionar Región";
cbx_region.addItem(
new Regiones(
a,
c
)
);
}
else{
while(rs.next()){
cbx_region.addItem(
new Regiones(
rs.getInt("ID_REGION"),
rs.getString("NUM_REGION")+" - "+ rs.getString("NOMBRE_REG")
)
);
}
}
}
} catch (Exception ex) {
Logger.getLogger(Regiones.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public String toString(){
return nombre;
}
}
And to load the combobox, the code is this:
Regiones rg = new Regiones();
rg.cargarR(cbx_region);
But I do not know how to select a default region.