Megadec Megadec - 1 month ago 8
Java Question

Deleting an object from an Array list through a selected item from a JComboBox

I have a student enrolment system I am having trouble with. I'm trying to remove an object from an

ArrayList
by selecting it from a
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());
}
}
);


I have added a string from the object to show on the
JComboBox
, so what I am trying to do is select that item (shown by Students name) and then delete the selected item.

Answer

To help anyone else with a similar problem, I solved the solution by doing the following:

    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);
                    }
                }
            }
        }
    });
Comments