Pick object id attribute selected in Jcombobox

Asked

Viewed 1,423 times

1

I have a table in BD with Columns Id, Board N° and Drilling on board.

I’d like to show on JComboBox the concatenation of "Plate N° + Drilling".

Example:

Plate 10 - 113,00 mm

But when a combobox item is selected by the user, capture the corresponding object ID Placa. I’m doing it in Netbeans and Mysql.

Follow the method you search in the bank (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 Board 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 (From the 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 cannot complete the reasoning of the Control part, to get the id of the selected item.


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

placa.add(pl); 

And I populate the Combobox (Hurricane Values) using the Model 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 error occurs below:

inserir a descrição da imagem aqui

  • You have created a proper Combomodel for the board class?

  • diegofm, I tried to do this topic... http://respostas.guj.com.br/1430-buscar-id-do-campo-selected-no-combobox-resolver public class Combomodeltipo extends Abstractlistmodel Implements Comboboxmodel {

  • Add a [mcve] to simulate the problem, read more here

1 answer

2


The cause of the exception

The method getElementAt() must 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

To display the information in the combo without affecting the object type is 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 chose to use the class DefaultListCellRenderer because it not only implements the interface ListCellRenderer as well as other features to avoid having to 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 the casting for your object Placa and call the method that returns the ID:

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

No need to create a ComboBoxModel(in case the getIdObjetoSelecionado()) to redeem the id of the selected object, once you already know that the getSelectedItem return a type object Placa, the above solution already covers this.

  • Ok diegofm, now it’s working cool!

  • @Rafb-- good, anything, just warn :)

  • @Rafb-- in future questions, it is interesting you add the error in text form instead of photo, because in text it makes it easier to search for the problem, if others have one similar to yours.

  • Just a curiosity: How can I display the "Select" in the Combobox? Ates it popular the combo. I think it would have to be something inside the Placacomborenderer.

  • @Rafb-- see the edition in the class PlacaComboRenderer , was the most simplistic and "crude" way I found, without having to distort the doubt of that question. After something is selected, the message disappears and does not return until the application is reopened. If you want something more elaborate than this to display a default option, then you will have to create a new question with a [mcve] from combo to test.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.