gpt4 book ai didi

Java Combobox,管理数据库中的 2 个字段

转载 作者:行者123 更新时间:2023-12-01 08:13:37 25 4
gpt4 key购买 nike

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

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

然后我想在组合框中显示名为“name_prov”的字段(作为项目)。但我也希望将我的“id_prov”(即 ID(主键))作为该项目的值。其目的是仅通过使用组合框将名称(在本例中为提供者的名称)与其 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 );
}

我可以完成这个任务吗?

最佳答案

首先创建一个 POJO,它将保存您的名称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 对象放入您的 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.
}
});

关于Java Combobox,管理数据库中的 2 个字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15332113/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com