Search code examples
javaswingarraylistactionlistener

Using ActionListener to add and remove items from List


I'm trying to use JFrame and action listener to create (what should be) a simple program for a student to add and drop courses. My drop courses button is not working (and I'm not convinced my add courses button is working properly either). I think my issue is that I'm creating a new Course object with each action listener so the dropCourse method is not finding the object in the list. However, I can't figure out how to have the listener use the info in my Jframe to determine if the item exists in the list already... I'm very new to Java and I'm sure this isn't the only issue with my code... It's just the one I've spent the last 2 days trying to fix.

A course just has a subject (courseType) and a number (courseNumType).

I've pasted the full code for both classes below, but I believe the issue is my action listener creates a new object, then calls a dropClass() method (which is really a list.remove()). But I'm not sure how to pass the correct values without creating a new object.

JButton dropButton = new JButton("Drop Course");
            dropButton.setBounds(120, 210, 160, 20);
            dropButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    // TODO Auto-generated method stub
                    
                
                Student studentobj = new Student(fNametxt.getText(), lNametxt.getText(),stuEmailtxt.getText(), dobtxt.getText(), stuList);
                Course courseobj = new Course (courseTypeBox.getSelectedItem().toString(), (int)courseNumTypeBox.getSelectedItem());
                
                studentobj.dropCourse(courseobj);
                }
                
                
            });

This is my main method and class to create the GUI and implement the action listener:

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.List;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

public class SIS_GUI {

  public SIS_GUI() {
    createStudentGUI();
  }


    private void createStudentGUI() {
        // TODO Auto-generated method stub
        List<Course> stuList = new ArrayList<>();

        JFrame jframe = new JFrame("Tom's Wonderful Student Information System");
        jframe.setLayout(new GridLayout(8, 4));
        JLabel fName = new JLabel("Enter Student First Name");
        fName.setBounds(10, 50, 150, 20);
        JTextField fNametxt = new JTextField(" ");
        fNametxt.setBounds(150, 50, 150, 20);
        JLabel lName = new JLabel("Enter Student Last Name");
        lName.setBounds(10, 150, 150, 20);
        JTextField lNametxt = new JTextField(" ");
        lNametxt.setBounds(350, 150, 150, 20);
        JLabel stuEmail = new JLabel("Enter Student Email");
        stuEmail.setBounds(10, 90, 150, 20);
        JTextField stuEmailtxt = new JTextField(" ");
        stuEmailtxt.setBounds(200, 90, 150, 20);
        JLabel dob = new JLabel("Enter Date of Birth");
        dob.setBounds(10, 130, 150, 20);
        JTextField dobtxt = new JTextField(" ");
        dobtxt.setBounds(200, 130, 150, 20);
        JLabel course = new JLabel("Select Course Name");
        course.setBounds(10, 170, 150, 20);
        String[] courseType = { "Biology", "Computer Science", "Philosophy" };
        JComboBox courseTypeBox = new JComboBox(courseType);
        //courseTypeBox.setBounds(200, 170, 150, 20);
        JLabel courseNum = new JLabel("Select Course Number");
        course.setBounds(10, 170, 150, 20);
        Integer[] courseNumType = { 101, 202, 303 };
        JComboBox courseNumTypeBox = new JComboBox(courseNumType);
        //courseNumTypeBox.setBounds(200, 170, 150, 20);
        JButton addButton = new JButton("Add Course");
        addButton.setBounds(120, 210, 160, 20);
        addButton.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                // TODO Auto-generated method stub
                
                //String selectedCourseName = courseTypeBox.getSelectedItem().toString();
                //int selectedCourseNum = (int) courseNumTypeBox.getSelectedItem();
                
                Student studentobj = new Student(fNametxt.getText(), lNametxt.getText(),stuEmailtxt.getText(), dobtxt.getText(), stuList);
                Course courseobj = new Course(courseTypeBox.getSelectedItem().toString(), (int)courseNumTypeBox.getSelectedItem());
                
                studentobj.addCourse(courseobj);
                
            }
        });
            JButton dropButton = new JButton("Drop Course");
            dropButton.setBounds(120, 210, 160, 20);
            dropButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    // TODO Auto-generated method stub
                    
                //String selectedCourseName = courseTypeBox.getSelectedItem().toString();
                //int selectedCourseNum = (int)courseNumTypeBox.getSelectedItem();
                
                Student studentobj = new Student(fNametxt.getText(), lNametxt.getText(),stuEmailtxt.getText(), dobtxt.getText(), stuList);
                Course courseobj = new Course (courseTypeBox.getSelectedItem().toString(), (int)courseNumTypeBox.getSelectedItem());
                
                studentobj.dropCourse(courseobj);
                }
                
                
            });
            
            JButton viewButton = new JButton("View Courses");
            viewButton.setBounds(120, 210, 160, 20);
            viewButton.addActionListener(new ActionListener() {

                @Override
                public void actionPerformed(ActionEvent e) {
                    // TODO Auto-generated method stub
                    
                    
                    Student studentobj = new Student(fNametxt.getText(), lNametxt.getText(),stuEmailtxt.getText(), dobtxt.getText(), stuList);
                    
                    System.out.println(studentobj.toString());
                    
                }
            });
        
        jframe.add(fName);
        jframe.add(fNametxt);
        jframe.add(lName);
        jframe.add(lNametxt);
        jframe.add(stuEmail);
        jframe.add(stuEmailtxt);
        jframe.add(dob);
        jframe.add(dobtxt);
        jframe.add(course);
        jframe.add(courseTypeBox);
        jframe.add(courseNum);
        jframe.add(courseNumTypeBox);
        jframe.add(addButton);
        jframe.add(dropButton);
        jframe.add(viewButton);
        jframe.setSize(1000, 800);
        jframe.setVisible(true);
        jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        new SIS_GUI();
    }

}

And this is my code for the student class with the addCourse() and dropCourse() methods:

import java.util.List;


public class Student {
  private String fName;
  private String lName;
  private String email;
  private String DOB;
  private List<Course> courses;

  public Student() {

  }

      public Student(String fName, String lName, String email, String dOB, List<Course> courses) 
  {
    super();
    this.fName = fName;
    this.lName = lName;
    this.email = email;
    DOB = dOB;
    this.courses = courses;
}

public void addCourse(Course course) {
     courses.add(course);
     
}

public void dropCourse(Course course) {
    
    int index = courses.indexOf(course);
    
    courses.remove(index);

}

public List<Course> viewCourses() {

    return courses;

}



public String getfName() {
    return fName;
}

public String getlName() {
    return lName;
}

public String getEmail() {
    return email;
}

public String getDOB() {
    return DOB;
}


public String toString() {

    String str;
    if(courses.size()>0) {
         str = fName + " " + lName + "\nEmail address: " + email + "\nDate of birth: " + DOB
    
            + "\n";
            
    for(int i=0; i < courses.size(); i++) {
    str +=  courses.get(i).getCourseName() + " " + courses.get(i).getCourseID() +"\n";
        
    }}
    
    else
         str = fName + " " + lName + "\nEmail address: " + email + "\nDate of birth: " + DOB
                
                + "\nis not registered for any classes";

    return str;

  }

}

Course class:

public class Course {

private String courseName;
private int courseID;
//private int capacity;

public Course() {
    
}

public Course(String courseName, int courseID /*,int capacity*/) {

    this.courseName = courseName;
    this.courseID = courseID;
    //this.capacity = capacity;
}

public String getCourseName() {
    return courseName;
}

public void setCourseName(String courseName) {
    this.courseName = courseName;
}

public int getCourseID() {
    return courseID;
}

public void setCourseID(int courseID) {
    this.courseID = courseID;
}

public boolean contains(Course course) {
    // TODO Auto-generated method stub
    return false;
}

public int indexOF(Course course) {
    // TODO Auto-generated method stub
    return 0;
}



//  public int getCapacity() {
//      return capacity;
//  }
//
//  public void setCapacity(int capacity) {
//      this.capacity = capacity;
//  }



   
  
}

Solution

  • So before getting to the actual problem I think you can actually write down a spare JFrame class like so

    public class StudentGUI extends JFrame implements ActionListener {
       
       ...
    
        private void createStudentGUI() {
          // TODO Auto-generated method stub
          List<Course> stuList = new ArrayList<>();
    
          ...
          JButton dropButton = new JButton("Drop Course");
          dropButton.setBounds(120, 210, 160, 20);
          dropButton.addActionListener(this);
    
          ...
        }
       
        public void actionPerformed(ActionEvent action) {
            switch(action.getActionCommand()) {
                case "Drop Course":
                    //do something
                    break;
                default:
                    System.out.println("The action is not yet defined");
            }
        }
    }
    

    With this said... you have to make sure that the Course class correctly implements its own equals method, otherwise it's going to compare the address of the object which of course is not going to be the same since you're intantiating a new course inside the drop button action.

    Therefore you will have

    public class Course {
       
        ...
        
        @Override
        public boolean equals(Object o) {
           if(o instance of Course) {
              //set your own conditions like return this.courseId.equals(o.getCourseId);
           }
        }
    }
    

    Now the remove(Object) of the Collection you are using is actually going to use your method (equals) to compare the objects and find the one to remove.