Get selected object id attribute in JComboBox

1

I have a table in the DB with Id Columns, Number Plate, and Drill on the board.

I would like to show in the JComboBox the concatenation of "Plate N ° + Drilling".

Example:

  

Plate 10 - 113.00 mm

But when a combobox item is selected by the user, it captures the corresponding ID of the Placa object. I'm doing it in Netbeans and MySQL.

Follow the method that searches the database (DAO):

public ArrayList<Placa> ObterTabelaPlaca() {
    conectar();
    ArrayList<Placa> placa = new ArrayList<Placa>();
    Statement stmt = null;
    ResultSet rs = null;
    String sql = "SELECT * FROM cadastroplaca ORDER BY CAST(furoPL AS DECIMAL(5,2))";
    try {
        stmt = con.createStatement();
        rs = stmt.executeQuery(sql);
        while (rs.next()) {
            Placa pl = new Placa();
            pl.setId(rs.getInt("id"));
            pl.setCodPlaca(rs.getInt("codigoPL"));
            pl.setFuracao(rs.getDouble("furoPL"));
            placa.add(pl);
        }
    } catch (Exception e) {
        System.out.println("Erro " + e.getMessage());

    }
    return placa;
}

The Plate class (Model):

public class Placa {
    int codPlaca, qtdMoldePlaca, id;
    double furacao;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
    String notaPlaca;

    public int getCodPlaca() {
        return codPlaca;
    }

    public void setCodPlaca(int codPlaca) {
        this.codPlaca = codPlaca;
    }

    public int getQtdMoldePlaca() {
        return qtdMoldePlaca;
    }

    public void setQtdMoldePlaca(int qtdMoldePlaca) {
        this.qtdMoldePlaca = qtdMoldePlaca;
    }

    public double getFuracao() {
        return furacao;
    }

    public void setFuracao(double furacao) {
        this.furacao = furacao;
    }

    public String getNotaPlaca() {
        return notaPlaca;
    }

    public void setNotaPlaca(String notaPlaca) {
        this.notaPlaca = notaPlaca;
    }


}

The method that fills the component (Do controller):

 public void MostraComboPlaca() throws SQLException{
        CadastroDAO dao = new CadastroDAO();        
        ArrayList<Placa> listaplaca = dao.ObterTabelaPlaca();
        DecimalFormat formato = new DecimalFormat("#0.00");
        placaCilindrico.setModel(new ComboModelTipo(listaplaca));
        for(int i=0;i<listaplaca.size();i++){ 
        placaCombo.addItem(String.valueOf(formato.format(listaplaca.get(i).getFuracao()).replace('.', ','))+" - PL "+listaplaca.get(i).getCodPlaca());
        }
 }

I can not complete the reasoning of the Control part, to get the id of the selected item.

I store the details of the table in ArrayList with DAO above.

placa.add(pl); 

And populate the ComboBox (Values Drilling) using the Template below:

public void MostraComboPlaca() throws SQLException{
    CadastroDAO dao = new CadastroDAO();        
    ArrayList<Placa> listaplaca = dao.ObterTabelaPlaca();
    placaCombo.setModel(new ComboModelTipo(listaplaca));

 }

I use this class as ComboBoxModel:

public class ComboModelTipo extends AbstractListModel implements ComboBoxModel {

private ArrayList<Placa> lista;
private Placa selected;

public ComboModelTipo(ArrayList<Placa> lista) {
    this.lista = lista;
}

@Override
public int getSize() {
    return this.lista.size();
}

@Override
public Object getElementAt(int index) {
    return this.lista.get(index).getFuracao();
}

@Override
public void setSelectedItem(Object anItem) {
    this.selected = (Placa) anItem;
}

@Override
public Object getSelectedItem() {
    return this.selected;
}

public Integer getIdObjetoSelecionado() {
return selected.getId();
}
}

After these steps my ComboBox is populated, but when I click on some value, the following error occurs:

    
asked by anonymous 28.11.2016 / 20:04

1 answer

2

The cause of the exception

The method getElementAt() should return the selected object in the list, not its attribute, as you are doing. Change the method below as follows:

@Override
public Object getElementAt(int index) {
    return this.lista.get(index);
}

Changing the display of items in ComboModel

Displaying the information in the combo without affecting the object type is by using a ListCellRenderer :

public class PlacaComboRenderer extends DefaultListCellRenderer{
    @Override
    public Component getListCellRendererComponent(
            JList<?> list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
        super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);

        if (value instanceof Placa) {
            Placa placa = (Placa) value;
            DecimalFormat formato = new DecimalFormat("#0.00");
            String text = String.valueOf(formato.format(placa.getFuracao()).replace('.', ','))+" - PL "+ placa.getCodPlaca();
            setText(text);
        } else if(value == null) {
            setText("Selecione uma placa:");
        }
        return this;
    }
}

In this case, I have chosen to use the DefaultListCellRenderer class because it not only implements the ListCellRenderer interface but also brings other functionality in order to avoid terms that implement a complete ListCellRenderer from scratch.

To apply, just do this:

 public void MostraComboPlaca() throws SQLException{
        CadastroDAO dao = new CadastroDAO();        
        ArrayList<Placa> listaplaca = dao.ObterTabelaPlaca();
        DecimalFormat formato = new DecimalFormat("#0.00");
        placaCilindrico.setModel(new ComboModelTipo(listaplaca));
        //precisa ser exatamente após o ComboBoxModel ser aplicado
        placaCombo.setRenderer(new PlacaComboRenderer());
}

And to capture items from this JComboBox , just grab the selected item, do casting for your Placa object and call the method that returns the ID:

Placa placaSelecionada = (Placa)seuCombo.getSelectedItem();
int id = placaSelecionada.getId();

You do not need to create a method in ComboBoxModel (in this case getIdObjetoSelecionado() ) to retrieve the id of the selected object, since you already know that getSelectedItem will return an object type Placa , the above solution already covers that.

    
29.11.2016 / 11:32