首页 > 解决方案 > 使用 ActionListener 在 List 中添加和删除项目

问题描述

我正在尝试使用 JFrame 和动作侦听器来创建(应该是)一个简单的程序,供学生添加和删除课程。我的降级课程按钮不起作用(而且我不相信我的添加课程按钮也可以正常工作)。我认为我的问题是我正在为每个动作侦听器创建一个新的 Course 对象,因此 dropCourse 方法没有在列表中找到该对象。但是,我不知道如何让侦听器使用我的 Jframe 中的信息来确定该项目是否已经存在于列表中......我对 Java 很陌生,我确信这不是唯一的我的代码有问题...这只是我过去 2 天试图修复的问题。

一门课程只有一个主题(courseType)和一个数字(courseNumType)。

我已经粘贴了下面两个类的完整代码,但我认为问题是我的动作侦听器创建了一个新对象,然后调用了一个 dropClass() 方法(这实际上是一个 list.remove())。但我不确定如何在不创建新对象的情况下传递正确的值。

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

这是我创建 GUI 和实现动作监听器的主要方法和类:

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

}

这是我的带有 addCourse() 和 dropCourse() 方法的学生类的代码:

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;

  }

}

课程类别:

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;
//  }



   
  
}

标签: javaswingarraylistactionlistener

解决方案


因此,在解决实际问题之前,我认为您实际上可以像这样写下一个备用的 JFrame 类

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

话虽如此...您必须确保 Course 类正确实现其自己的equals方法,否则它将比较对象的地址,这当然不会相同,因为您正在实例化一门新课程在下拉按钮操作中。

因此,您将拥有

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

现在,您正在使用的 Collection 的 remove(Object) 实际上将使用您的方法(等于)来比较对象并找到要删除的对象。


推荐阅读