2013-03-09 58 views
1

我有一個學生註冊系統,我遇到了麻煩。我試圖通過從JComboBox中選擇一個從ArrayList中刪除對象。通過JComboBox中的選定項目從陣列列表中刪除對象

public class Course { 

public List<Student> Students; 
public List<Module> Modules; 

    public Course() 
    { 
     Students = new ArrayList<Student>(); 
     Modules = new ArrayList<Module>(); 
    } 

public class Del_Student extends JFrame 
{ 

    private Course newCourse; 
    public Del_Student(Course aCourse) 
    { 
     newCourse = aCourse; 
     JButton btnDel = new JButton("Delete"); 
     JButton btnCancel = new JButton("Cancel"); 
     JComboBox studentsBox = new JComboBox(); 
     studentsBox.setPreferredSize(new Dimension(185,25)); 

    for(int i=0; i<newCourse.Students.size();i++) 
    { 
     String p = newCourse.Students.get(i).getFirstName(); 
     studentsBox.addItem(p); 
    } 

     btnDel.addActionListener 
    (
     new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
       newCourse.Students.remove(studentsBox.getSelectedItem()); 
      } 
     } 
    ); 

我已經加入從對象的字符串顯示在JComboBox,所以我試圖做的是選擇該項目(由學生名字所示),然後刪除選定的項目。

回答

2

爲了幫助其他人有類似的問題,我解決了這樣的解決方案如下:

btnDel.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      for (int i = 0; i < newCourse.Students.size(); i++) { 
       if (newCourse.Students.get(i).getFirstName().equals(studentsBox.getSelectedItem() 
         .toString())) { 
        newCourse.Students.remove(i); 
        JOptionPane.showMessageDialog(null, "Student Deleted"); 
        studentsBox.removeAllItems(); 
        for (int t = 0; t < newCourse.Students.size(); t++) { 
         String p = newCourse.Students.get(t).getFirstName(); 
         studentsBox.addItem(p); 
        } 
       } 
      } 
     } 
    }); 
+1

你是不是應該比較兩個字符串與.equals(),而不是「==」操作符?只是想指出,如果它有幫助 – Carlton 2016-10-26 17:21:04

+1

你是正確的卡爾頓,答案已更新。 – Megadec 2016-10-27 06:44:41