Set Value and Label to JComboBox

醉酒当歌 提交于 2019-12-02 03:05:01

问题


I have a JComboBox where the items are the results of a query. The combo shows all the categories names taken from a query, right? Ok, it works. Now I need to give each item a value, which would be the ID of the product.

This is what I've got so far:

    final JComboBox proveedorCombo = new JComboBox();

    contentPanel.add(proveedorCombo);

    ProveedorDAO dao = new ProveedorDAO();

    List<Proveedor> proveedor = dao.getAll();

    Object[][] elementos = new Object[proveedor.size()][2];

    for (int i = 0; i < proveedor.size(); i++) {
        Proveedor p = proveedor.get(i);
        elementos[i][0] = p.getId();
        elementos[i][1] = p.getNombre();
        proveedorCombo.addItem(elementos[i][1]);
    }

As you can see in the code, the "label" of each item is the name of it. Now, how can I set each item its ID so I can manipulate after?

Thanks and try to answer easily, I'm having the hardest time trying to get this Java thing! Ha!


回答1:


JComboBox by default uses a renderer wich uses toString() method to display object data. So you can make your own render class to customize the view.

This is the way it was designed for.

proveedorCombo.setRenderer( new DefaultListCellRenderer(){

        @Override  
        public Component getListCellRendererComponent(
            JList list, Object value, int index,
            boolean isSelected, boolean cellHasFocus)
        {
            super.getListCellRendererComponent(list, value, index,
                isSelected, cellHasFocus);

                if(value != null){
                 Proveedor proveedor = (Proveedor)value;
                 setText( proveedor.getName());
                }
            return this;
        }
});

Another hacky approach is overriding toString() from Proveedor or making your adapter class that uses your toString() but this solution is not much flexible as the other one.

public class Proveedor {

//in some part
@Override
public String toString(){
    return this.nombre;
}

}

In the combobox if you want to populate from zero.

proveedorCombo.setModel(new DefaultComboBox(new Vector<Proveedor>(dao.getAll())));

Or if you have previous data and you want to maintain.

for(Proveedor p : dao.getAll){
    proveedorCombo.addItem(p);
}


来源:https://stackoverflow.com/questions/18024246/set-value-and-label-to-jcombobox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!