Java组合框,管理数据库中的2个字段

ac1kyiln  于 2023-01-29  发布在  Java
关注(0)|答案(2)|浏览(108)

我想从我的数据库中得到一个有2个字段的结果集。

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

然后我想在comboBox中显示名为“name_prov”的字段(作为项目)。但是我还想把我的“id_prov”,即ID(主键)作为这个项目的值。这样做的目的是通过使用comboBox将名称(在本例中是提供者的名称)与其ID关联起来。
这是我目前使用的JComboBox事件FocusGained的代码。

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

有什么办法能让我做到吗?

4ioopgfo

4ioopgfo1#

首先创建一个POJO,它将同时包含nameid

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对象将其放入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  );
    }

最后,要选择值,您可以这样做:-

CBProv.addActionListener(new ActionListener() {

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

c90pui9n2#

你好,我也是java和javafx的新手。这是我在javafx中做的,它对我很有效,希望你能在java中解决它。

private void fillProviders()
  {
    List<String> providerList = new ArrayList<String>();

  try
    {   
        String Sql = "select * from prov ";
        pat= conn.prepareStatement(Sql);
        rs=pat.executeQuery();

        while (rs.next())
        {
            providerList.add(rs.getString("id_prov")+" "+ rs.getString("name_prov"));
        }

        ObservableList<String> provider =  FXCollections.observableArrayList(providerList);
            bankName.setItems(provider);  
    }

    catch( Exception e)
    {
        JOptionPane.showMessageDialog(null, e);
    }         
}

希望它对你有用。注意我的我的组合框名称是bankName

相关问题