问题描述
当我从database
获取category_id
和category_name
时,我想使用swing
将值设置为JComboBox
例如cat_id
作为索引, cat_name
作为项。
public DefaultComboBoxModel getCategoryItems()
{
con=ConnectionClass.getConnection();
DefaultComboBoxModel categoryItems = new DefaultComboBoxModel();
try
{
PreparedStatement getCatStmt=con.prepareStatement("select cat_id,cat_name from category", ResultSet.CONCUR_UPDATABLE, ResultSet.TYPE_SCROLL_SENSITIVE);
ResultSet catRS=getCatStmt.executeQuery();
while (catRS.next()) {
categoryItems.addElement(catRS.getString("cat_name"));
//Here, I want to set index id and value
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(CategoryDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
return categoryItems;
}
1楼
您需要做的是创建另一个类(例如Category)以同时容纳cat_id和cat_name。 如下所示:
class Category {
int id ;
String name ;
public String toString() {
return name ;
}
}
从结果集中添加具有ID和名称的新类别。 选择该项目后,所选内容将是“类别”对象,可从其中检索cat_id。 请记住重写toString()-因为这是ComboBox显示的内容。
2楼
public class Item
{
private int id;
private String description;
public Item(int id, String description)
{
this.id = id;
this.description = description;
}
public int getId()
{
return id;
}
public String getDescription()
{
return description;
}
public String toString()
{
return description;
}
}
public DefaultComboBoxModel getCategoryItems()
{
con=ConnectionClass.getConnection();
DefaultComboBoxModel categoryItems = new DefaultComboBoxModel();
try
{PreparedStatement getCatStmt=con.prepareStatement("select cat_id,cat_name from category ", ResultSet.CONCUR_UPDATABLE, ResultSet.TYPE_SCROLL_SENSITIVE);
ResultSet catRS=getCatStmt.executeQuery();
while (catRS.next()) {
categoryItems.addElement( new com.hotel.bean.Item(catRS.getInt("cat_id"), catRS.getString("cat_name") ) );
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
try {
con.close();
} catch (SQLException ex) {
Logger.getLogger(CategoryDao.class.getName()).log(Level.SEVERE, null, ex);
}
}
return categoryItems;
}