How to convert to Integer getSelectedItem () from a JComboBox in Java

0

I tried the following but it does not compile the code:

Integer seleccion = (Integer)jcombo.getSelectedItem();

Also with:

Integer seleccion = Integer.parseInt(jcombo.getSelectedItem());

and with:

Integer seleccion = Integer.valueOf(jcombo.getSelectedItem());

I would appreciate your help!

    
asked by Mauricio Ricardo 12.11.2017 в 05:29
source

3 answers

1

The method jcombo.getSelectedItem () returns Object and you will not be able to recover its value in this way, I understand that what you need is to obtain the value of the selected ID. You can achieve it with some functions, First We create a class that will manage the loads of any combox that we want.

    package Genericos;

   import java.sql.PreparedStatement;
   import java.sql.ResultSet;
   import java.sql.SQLException;
   import java.util.ArrayList;
   import java.util.logging.Level;
   import java.util.logging.Logger;

  public class PrepararDatosCombos {
  private ResultSet rs;
  private PreparedStatement ps;
  private ArrayList<comboItem> lista;
  private comboItem item;

 /*
Realizamos un select de tipo id,descripcion solo dos columnas
cargamos el array.
*/
public PrepararDatosCombos(String query) {
    try {
        ConexionDB.getInstancia();
        ps=ConexionDB.getDBcon().prepareStatement(query);
        rs=ps.executeQuery();
        lista=new ArrayList<>();
        while (rs.next()) {                
          //nuevo objeto
          item=new comboItem();
          item.setId(rs.getInt(1));
          item.setDescrip(rs.getString(2));
          //agregando el objeto a la lista
          lista.add(item);
        }
    } catch (SQLException ex) {
               Logger.getLogger(PrepararDatosCombos.class.getName()).log(Level.SEVERE, null, ex);
    }
}

/*
Retorna El array con los valores del Select
*/
public ArrayList<comboItem> getItemsCombo(){
    return lista;
}

/*
Retorna el id del Elemento seleccionado en el combox mediante su Posicion
*/
public Integer getIdSegunIndice(Integer indice){

return (indice >= 0 ? lista.get(indice).getId() : 0);

}

/*
Nuestra clase para El ArrayList
*/
public class comboItem{
    private Integer id;
    private String descrip;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getDescrip() {
        return descrip;
    }

      public void setDescrip(String descrip) {
        this.descrip = descrip;
      }
   }
 }

Now in the class that we want to use it, we do the following. method to load the combox. We declare at the class level.

private PrepararDatosCombos Preparador;



public void cargarComboUbicaccion() {
    //perfiles
    Sql ="SELECT id_ubi, descripcion FROM ubic_producto ORDER BY id_ubi;";
    Preparador = new PrepararDatosCombos(Sql);
    stock.comboUbicacion.removeAllItems();
    for (PrepararDatosCombos.comboItem item : Preparador.getItemsCombo()) {
        comboUbicacion.addItem(item.getDescrip());
    }
}

Then the method that will recover the id of the selected item in the Combox.

public int  getIDUbicaccion() { 
   return Preparador.getIdSegunIndice(comboUbicacion.getSelectedIndex());    
}
    
answered by 22.09.2018 в 19:57
0

Since the element can be null , to avoid an NPE, do this:

Integer i = (Integer)jcombo.getSelectedItem();
if (i != null) {
    int seleccion = i; 
}else{
    int seleccion = 0; //Por si necesitas disponer a toda costa de una variable seleccion para evaluar algo
}
    
answered by 12.11.2017 в 05:49
0

You could try:

try {
     int numero  = Integer.parseInt(combo.getSelectedItem().toString());
}catch(NumberFormatException e ){
     //Capturas la excepcion si el elemento del combo no es un numero.
     System.out.println("El elemento seleccionado no es un numero");
}

The only difference with A.Cedano's answer is that in my case I do not use the Integer class, but simply "int", maybe that's why it does not work correctly. I hope my answer will help.

    
answered by 13.11.2017 в 09:22