将值和标签设置为JComboBox [英] Set Value and Label to JComboBox

查看:100
本文介绍了将值和标签设置为JComboBox的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JComboBox,其中的项目是查询的结果.该组合显示了从查询中获取的所有类别名称,对吗?好的,它可以工作.现在,我需要为每个项目赋予一个值,该值就是产品的ID.

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]);
    }

如您在代码中所见,每个项目的标签"是它的名称.现在,如何设置每个项目的ID,以便以后进行操作?

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?

感谢并尝试轻松回答,我最难尝试获取Java东西!哈!

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

推荐答案

JComboBox默认情况下使用渲染器,而使用toString()方法显示对象数据.因此,您可以创建自己的渲染类以自定义视图.

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.

这是它的设计方式.

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;
        }
});

另一种骇人听闻的方法是从Proveedor覆盖toString()或使适配器类使用您的toString(),但是此解决方案不像其他解决方案那样灵活.

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);
}

这篇关于将值和标签设置为JComboBox的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆