2013-03-03 27 views
1

好吧,即時嘗試從我的數組中刪除一個對象,每個對象都有一個用戶ID,所以數組中的0索引將持有ID爲1的對象。當我刪除對象wih id爲2例如我想刪除數組中的1索引並重做模型並顯示它。所以我希望模型顯示1:胡說,然後3:胡說等留出刪除的文件從數組中刪除,但保持秩序?

private void DeleteButtonActionPerformed(java.awt.event.ActionEvent evt) { 

// arrays index not working when deleted 
int reply = JOptionPane.showConfirmDialog(null, "Are you sure?","Delete Patient: " +  
NameTextField.getText(), JOptionPane.YES_NO_OPTION); 
    if (reply == JOptionPane.YES_OPTION) { 

     int Num = Integer.parseInt(IDTextField.getText()); 
     int Num1 = Num--; 


     for(Patient s: PatientList) 
     { 

      if(Num == s.getAccountNumber()) 
      { 
       PatientList.remove(Num1); 
       break; 

      } 
     } 

     DefaultListModel PatientListModel = new DefaultListModel(); 

    for(Patient s: PatientList) 
    { 

    PatientListModel.addElement(s.getAccountNumber() + "-" + s.getName()); 
} 
    PatientJList.setModel(PatientListModel); 

    //delete procedures for that id 



     JOptionPane.showMessageDialog(null, "Patient: " + NameTextField.getText() + "  

Deleted!"); 
     NameTextField.setText(""); 
    AgeTextField.setText(""); 
    AddressTextField.setText(""); 
    SexGroup.clearSelection(); 
    PhoneTextField.setText(""); 
    IDTextField.setText(""); 
    PatientJList.clearSelection(); 


    } 
    else { 


    } 
} 
+2

而你的問題是?你爲什麼不尊重Java命名約定? – 2013-03-03 17:40:11

回答

2

我相信,而不是使用數組索引爲對象id你應該在對象維修器材這個屬性本身。喜歡的東西:

public class Patient { 

    private int id; 

    // getter and setter for id 

    // rest of the class 

} 
+0

我確實在患者類中有這樣的情況,當從患者列表中刪除一個對象時,我會循環訪問它們,並且如果id num與您輸入的要刪除的num相符,則在患者列表中刪除num-1。 這有道理嗎? – 2013-03-03 18:47:02

+0

在顯示時,您可以調用'getId',而不是在迭代列表時依賴數組索引。 – 2013-03-03 18:54:55

0

Object你所談論的,保持一個更多的財產在叫index。在將此對象添加到數組時,將Object.index設置爲數組的索引。

現在做任何你想要的數組。但在顯示數組時。像這樣做

Object.index Object