2014-12-07 89 views
0

什麼是檢查JComboBox中的重複項目並刪除它們的最佳方法?根據我所研究的情況,這在Java中並沒有真正得到解答。基本上,當我用觀察者模式刷新我的JComboBox時,它會在更新時複製項目。我嘗試過去除所有項目並重新放入項目的路線,但這會在修改項目信息時引發問題(需要很長時間才能完整解釋)。刪除重複的項目JComboBox

public void setCustomers() 
{ 

for (Customer curr : Main.getNewCustomerList().getCustomers()) 
{ 

    customerCombo.addItem(curr); 

} 


} 


public void setDetails() 
{ 
Customer selected = (Customer) customerCombo.getSelectedItem(); 
if(selected != null) 
{ 
forenameText.setText(selected.getForename()); 
surnameText.setText(selected.getSurname()); 
costperkgText.setText(String.valueOf(selected.getDeliveryCost())); 
line1Text.setText(String.valueOf(selected.getColAddress().getAddressLine1())); 
line2Text.setText(String.valueOf(selected.getColAddress().getAddressLine2())); 
cityText.setText(String.valueOf(selected.getColAddress().getCity())); 
postcodeText.setText(String.valueOf(selected.getColAddress().getPostcode())); 

} 
else 
{ 
    ClearText(); 
} 
} 

public void ammendDetails() 
{ 
Customer selected = (Customer) customerCombo.getSelectedItem(); 
if(selected != null) 
{ 
selected.setForename(forenameText.getText()); 
selected.setSurname(surnameText.getText()); 
System.out.print(costperkgText.getText()); 
selected.setDeliveryCost(Double.valueOf(costperkgText.getText())); 
Address newAddress = new Address(line1Text.getText(), line2Text.getText(), cityText.getText(), postcodeText.getText()); 
selected.setColAddress(newAddress); 


} 
else 
{ 
    ClearText();   
} 

} 

public void ClearText() 
{ 
forenameText.setText(""); 
surnameText.setText(""); 
costperkgText.setText(""); 
line1Text.setText(""); 
line2Text.setText(""); 
cityText.setText(""); 
postcodeText.setText(""); 
} 


@Override 
public void update() 
{ 
setCustomers(); 
} 

回答

1

試試這個

public void setCustomers(){ 

     customerCombo.removeAllItems(); 

     for (Customer curr : Main.getNewCustomerList().getCustomers()){ 

       customerCombo.addItem(curr); 

     } 


    } 
+0

這已經在我的問題排除在外,因爲它導致的細節,以當前選定客戶的詳細信息設置爲組合的第一個客戶修訂。 – bSky 2014-12-07 20:20:31

+0

1+,對我來說似乎是一個很好的解決方案。 「它會導致修改細節,以將當前選定客戶的詳細信息設置爲組合中的第一位客戶 - 不知道這意味着什麼。但是,如果您在選擇某個項目時說要做一些處理,那麼解決方案是刪除ActionListener,更新組合框,然後將ActionListener添加回組合框 – camickr 2014-12-07 21:11:21

+0

@bSky將當前選定的客戶保存在字段中在使用setCustomers重置視圖之前,再次設置先前選擇的客戶 – 2014-12-08 03:27:47