Set Value and Label to JComboBox

前端 未结 1 1698
无人共我
无人共我 2021-01-22 19:10

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 v

相关标签:
1条回答
  • 2021-01-22 19:26

    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);
    }
    
    0 讨论(0)
提交回复
热议问题