我有一个 JList,它根据数据库显示名称。与这些名称相关的是 ID。例如,foodId = 1,foodName = Chinese。
如果我单击 JList 上的某个项目,我需要捕获与单击的 foodName 关联的 foodID。我知道需要一个变量。
当我拥有该值时,我可以将该值传递给另一个方法来检索与该 foodId 关联的相关食品。假设 getter 和 setter 已经完成。
我只有以下内容,并且被卡住了。请指教谢谢。
list_1.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent evt) {
//alter text of Label acc to clicked item @ JList
JList list = (JList)evt.getSource();
System.out.println (list.getSelectedValue());
//store int value of item clicked @ JList
int temp = 0;
temp = ???????????
//populate JPanel
Food food = new Food();
JPanel panel = new JPanel();
panel.setBounds(153, 74, 281, 269);
panel.add(food.populateWithButtons());
contentPane.add(panel);
}
});
list_1.setBorder(new LineBorder(new Color(0, 0, 0), 0));
//populate JList
list_1.setModel(food.populateJList());
public ListModel populateJList()
{
DefaultListModel model = new DefaultListModel();
ResultSet rs = null;
DataAccessObject db = new DataAccessObject();
db.setUp("customer");
String dbQuery = "SELECT store_Owner_Id, food_Category FROM store_owner";
rs = db.readRequest(dbQuery);
try
{
while (rs.next())
{
food_Category = rs.getString("food_Category");
store_Owner_Id = rs.getInt("store_Owner_Id");
model.addElement(food_Category);
System.out.println (store_Owner_Id); //test DB conn & print retrieved items
System.out.println (food_Category);
}
}
catch (Exception e)
{
e.printStackTrace();
}
db.terminate();
return model;
}