我一直在用这种方法挣扎几个小时,这种方法有一种奇怪的行为。 场景:两个jlists,menuList和productList填充来自mysql db的数据,第一个包含“类别”,第二个包含该类别的产品。它们都填充了Vector对象。问题是,当我执行产品搜索时,除了在保存新菜单(类别)后立即可以在所有情况下正常工作。在这种情况下,menuList的索引已成功移动到我正在搜索的产品所在的正确类别,但productList保持空白。 这是进行搜索的方法的代码。
private void bFindProductActionPerformed(java.awt.event.ActionEvent evt) {
Product product = new Product();
product.setProductName(searchedProduct.getText());
bNewProduct.setEnabled(false);
Vector<Product> productVoices = DBConnection.searchProduct(product);
if (!productVoices.isEmpty()) {
modelProductList.clear();
disableProductButtons();
menuName.setText("");
productName.setText("");
int idMenu = 0;
for (int i = 0; i < productVoices.size(); i++) {
Product current = (Product) productVoices.get(i);
modelProductList.addElement(current);
idMenu = current.getMenuId();
}
productList.setModel(modelProductList);
for (int i = 0; i < modelMenuList.getSize(); i++) {
Menu current = (Menu) modelMenuList.getElementAt(i);
if (idMenu == current.getMenuId()) {
int currentId = modelMenuList.indexOf(current);
menuList.setSelectedIndex(currentId);
menuList.requestFocus();
}
}
} else {
JOptionPane.showMessageDialog(null, "No product found", "", JOptionPane.WARNING_MESSAGE);
searchedProduct.setText("Search...");
}
}
这是保存新菜单(或更新现有菜单)的方法代码:
private void bSaveMenuActionPerformed(java.awt.event.ActionEvent evt) {
//If there's a selected menu updates
if (!menuList.isSelectionEmpty()) {
Menu selectedMenu = (Menu) menuList.getSelectedValue();
listIndex = menuList.getSelectedIndex();
selectedMenu.setMenuName(menuName.getText());
int result = DBConnection.updateMenu(selectedMenu);
if (result == 1) {
reloadMenuList(); //this re-fill the menuList
menuList.setSelectedIndex(listIndex);
menuList.setEnabled(true);
bFindProduct.setEnabled(true);
bNewMenu.setEnabled(true);
bNewProduct.setEnabled(false);
}
} else { //If there isn't a selected menu, creates a new menu
Menu newMenu = new Menu();
newMenu.setMenuName(menuName.getText());
int result = DBConnection.insertMenu(newMenu);
if (result == 1) {
reloadMenuList();
newMenuIsSaved = true;
menuList.setEnabled(true);
bFindProduct.setEnabled(true);
}
}
}
谢谢。