Java Combobox,从数据库管理2字段 [英] Java Combobox, Managing 2 fields from database

查看:345
本文介绍了Java Combobox,从数据库管理2字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从我的数据库获得一个包含2个字段的结果集。

I want to get a result set with 2 fields from my DB.

 rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");

然后我想在comboBox(作为项目)中显示名为name_prov的字段。但我也想有我的id_prov这是ID(PRIMARY KEY)作为该项目的值。

And then I want to show the field called "name_prov" in the comboBox (As the item). But I also want to have my "id_prov" which is the ID (PRIMARY KEY) as the value for this item. This serves for the purpose of relating the name (of the providers in this case) with its ID just by using the combobox.

这是JComboBox事件的代码FocusGained(在这种情况下的提供者的名称)与它的ID只是通过使用组合框架的目的。

This is the code of the JComboBox event FocusGained that Im currently using.

try {
        //CBProv is the Combobox
        CBProv.removeAllItems();


        rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");

        while(rs.next())
        {

            CBProvedores.addItem(rs.getString("name_prov"));
            //Here should be the Value related to the item I am creating



        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Error" + e  );
    }

有没有我可以做到这一点?

Is there anyway I can accomplish this?

推荐答案

首先创建一个POJO,它将保存您的名称 / code>。

First create a POJO, which will hold both your name and id.

public class ComboItem {
    private String id;
    private String name;

    public ComboItem(String id, String name) {
        this.id = id;
        this.name = name;
    }

    // Add the getter and setter as you want.

    // This will be used internally by JComboBox as the label to be displayed.
    @Override
    public String toString() {
        return name;
    }
}

然后使用这个POJO对象, code> JComboBox

Then use this POJO objects to be put into your JComboBox.

try {
        //CBProv is the Combobox
        CBProv.removeAllItems();

        rs=Con.sqlQueryTable("Select id_prov, name_prov from prov");

        while(rs.next())
        {                
            String id = rs.getString("id_prov"); // Get the Id
            String name = rs.getString("name_prov"); // Get the Name

            ComboItem comboItem = new ComboItem(id, name); // Create a new ComboItem
            CBProv.addItem(comboItem); // Put it into the ComboBox

        }
    } catch (Exception e) {
        JOptionPane.showMessageDialog(this, "Error" + e  );
    }

然后最后得到选择的值,你可以这样做: / p>

And then finally to get the value selected, you can do this:-

CBProv.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                ComboItem comboItem = (ComboItem) CBProv.getSelectedItem();
                // comboItem.getId(), comboItem.getName() - Use as you wish.
            }
    });

这篇关于Java Combobox,从数据库管理2字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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