在我正在处理的应用程序中,我有一个用户可以基本上按名称搜索客户的地方......在GUI中有一个文本字段,用户应在其中输入他想要的客户名称搜索和搜索按钮。
当按下搜索按钮时,基本上会生成找到的客户列表,从中填充JList然后添加到外部面板......这里是代码,我让它进行说话..
public void actionPerformed(ActionEvent e)
{
String nameToSearchWith = customerSearchInput.getText();
Customer instance = new Customer();
ArrayList<Customer> foundCustomers = instance.FindCustomersByName(nameToSearchWith);
if (foundCustomers.size() > 0)
{
customerSearchInput.setText("");
FoundCustomersListModel foundCustomersListModel = new FoundCustomersListModel(foundCustomers);
JList foundCustomersList = new JList();
foundCustomersList.setModel(foundCustomersListModel);
foundCustomersList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
foundCustomersList.setLayoutOrientation(JList.VERTICAL);
foundCustomersList.setVisibleRowCount(-1);
foundCustomersListModel.update();
JScrollPane foundCustomersListScrollPanel = new JScrollPane(foundCustomersList);
//foundCustomersListScrollPanel.setPreferredSize(new Dimension(250, 80));
findCustomerPanel.add(foundCustomersListScrollPanel, BorderLayout.CENTER);
JButton customerDeleteButton = new JButton("Delete Selected Customer");
findCustomerPanel.add(customerDeleteButton, BorderLayout.SOUTH);
customerDeleteButton.setEnabled(false);
customerDeleteButton.addActionListener(new CustomerDeleteButtonListener(foundCustomersList, customerDeleteButton, foundCustomersListModel));
foundCustomersList.addListSelectionListener(new CustomerListSelectionListener(foundCustomersList, customerDeleteButton));
findCustomerPanel.revalidate();
}
else
{
JOptionPane.showMessageDialog (null,
"No customers where found with the given inputted name.",
"Error",
JOptionPane.ERROR_MESSAGE);
}
}
ListModel类的代码:
public class FoundCustomersListModel extends AbstractListModel
{
private ArrayList<Customer> foundCustomersList;
public FoundCustomersListModel(ArrayList<Customer> foundCustomersList)
{
this.foundCustomersList = foundCustomersList;
}
public void update()
{
this.fireContentsChanged(this, 0, (foundCustomersList.size() - 1));
}
@Override
public Object getElementAt(int index)
{
return(foundCustomersList.get(index));
}
@Override
public int getSize()
{
return(foundCustomersList.size());
}
@Override
public void addListDataListener(ListDataListener l) {}
@Override
public void removeListDataListener(ListDataListener l) {}
public void removeElementAt(int index)
{
foundCustomersList.remove(index);
this.fireIntervalRemoved(this, index, index);
}
}
我的问题是,如果我搜索名为Fabian的客户的示例,然后添加名为fabian的另一个客户,然后再次使用名称Fabian进行搜索,arraylist将正确更新,但JList不会,它仍将保持不变。
然后经过大量的研究后我发现我应该使用fireContentsChanged(),因此我已经实现了更新方法,你可以在上面看到并且它有效,但现在我遇到了另一个问题,这是现在所有名为fabian的客户都在JList中输出,但是在第一次搜索后添加的客户无法选择...如果按下它们没有任何反应,它们将不会突出显示。< / p>
此外,这非常奇怪,但如果我最小化应用程序然后再次最大化,JList会回到原来的状态,即没有最后添加的客户。
任何人都可以帮助我吗...也许这是因为线程并发......我不知道老实说对此没有太多了解...
由于