通过JComboBox中的选定项目从阵列列表中删除对象
问题描述:
我有一个学生注册系统,我遇到了麻烦。我试图通过从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
,所以我试图做的是选择该项目(由学生名字所示),然后删除选定的项目。
答
为了帮助其他人有类似的问题,我解决了这样的解决方案如下:
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);
}
}
}
}
});
你是不是应该比较两个字符串与.equals(),而不是“==”操作符?只是想指出,如果它有帮助 – Carlton 2016-10-26 17:21:04
你是正确的卡尔顿,答案已更新。 – Megadec 2016-10-27 06:44:41