我有一个 JComboBox,我必须显示产品的名称,每个产品都有一个代码名称, 在我的数据库中,我必须注册产品代码,但在组合中我必须显示名称,我应该如何在组合中显示名称,但将其代码保存在数据库中?
这是我的返回代码和指定代码
public ResultSet GetDesignation(JComboBox des)
{
ResultSet rs1 = null;
try {
conn=con.Connect();
stmt = conn.createStatement();
String rq1 = "SELECT designation, idproduit FROM produit";
rs1 = stmt.executeQuery(rq1);
while (rs1.next()) {
des.addItem(rs1.getString(1));
}
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
finally{
return rs1;
}
}
这是我获得 idproduct(代码)的代码
m.GetDesignation(des);
int designation=Integer.parseInt(des.getSelectedItem().toString());
最佳答案
不要直接填充 JComboBox
,而是创建类似 Product 类的内容,并在 while
循环的每次迭代中从 ResultSet
中提取 id 和产品名称,并将其设置为 Product 实例的属性。在 ArrayList
等集合中添加该 Product 实例,并使用它来填充您的 JComboBox
:
public class Product {
private int idProduct;
private String name;
public Product(int idProduct, String name) {
this.idProduct = idProduct;
this.name = name;
}
public int getIdProduct() {
return idProduct;
}
public void setIdProduct(int idProduct) {
this.idProduct = idProduct;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return name;
}
}
为您的 JComboBox
设置 DefaultComboBoxModel
并将数据添加到您的模型:
import javax.swing.*;
import java.awt.event.ItemEvent;
public class ComboDemo {
public static void main(String[] args) {
JComboBox<Product> comboBox = new JComboBox<>();
DefaultComboBoxModel<Product> defaultComboBoxModel = new DefaultComboBoxModel<>();
comboBox.setModel(defaultComboBoxModel);
defaultComboBoxModel.addElement(new Product(1, "Apples"));
defaultComboBoxModel.addElement(new Product(2, "Oranges"));
comboBox.addItemListener(e -> {
if (e.getStateChange() == ItemEvent.SELECTED) {
Product product = (Product) comboBox.getSelectedItem();
System.out.println(product.getName() + " ::: " + product.getIdProduct());
}
});
JOptionPane.showMessageDialog(null, comboBox);
}
}
在 JComboBox
上添加 ItemListener
并使用 getSelectedItem
从该 JComboBox
获取 Product
。因此,基本上,在这种情况下,您的 JComboBox
包含 Product
项及其所有属性,而不是像您的情况那样包含 String
。
关于java - 在 JComboBox 中显示属性并注册另一个属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30947656/