通过JComboBox中的选定项从数组列表中删除对象

时间:2013-03-09 11:07:27

标签: java arraylist 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上添加了一个来自对象的字符串,所以我要做的就是选择该项目(由学生姓名显示),然后删除所选项目。

1 个答案:

答案 0 :(得分: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);
                    }
                }
            }
        }
    });