繁体   English   中英

尝试从JList删除项目时出现逻辑错误

[英]Logical error when trying to remove an item from a JList

我有一个JList,它显示了我添加到数据库中的所有项目。 当我要删除多个项目时,例如说两个项目,其中只有一个会被删除。 这是我的代码:此方法来自我的类​​DAL:

public void removeStudent(Student student)throws SQLException{
  PreparedStatement studentStatement = getConnected().prepareStatement(
    "delete from student where spnr = ? and sname = ? and sadress = ? " +
     " and stel = ? ");

  studentStatement.setString(1, student.getIdNumber());
  studentStatement.setString(2, student.getName());
  studentStatement.setString(3, student.getAddress());
  studentStatement.setString(4, student.getTel());
  studentStatement.executeUpdate();
}

类控制器:

public void removeStudent(Student student) throws SQLException{
  dal.removeStudent(student);
}

和类View。 单击删除按钮时,在actionListener中使用。

private void removeStudent(){
  try{
    controller.getDal().getStudentData().getName();
    controller.getDal().getStudentData().getAddress();
    controller.getDal().getStudentData().getIdNumber();   
    controller.getDal().getStudentData().getTel();

    controller.removeStudent(controller.getDal().getStudentData());
  }catch(Exception e){
    e.printStackTrace();
  }
}

还有ActionEvent

if(infLst.getSelectedIndex() > -1){
  int choice = JOptionPane.showConfirmDialog(null, 
                 "Delete?" + "The student will be permamently deleted",
                 null,
                 JOptionPane.YES_NO_OPTION);
  if(choice == JOptionPane.YES_OPTION){
    //Removes from the JList            
    ((DefaultListModel)infLst.getModel()).removeElementAt(index);
    //And database 
    removeStudent();
  }else{
    return;
  }
}else{
  JOptionPane.showMessageDialog(null, "Please make sure you have selected an item from the list");
}
}}});

请考虑我是数据库编程领域的新手。 提前致谢。

当我要删除多个项目时,例如说两个项目,其中只有一个会被删除。

您的代码只有一个if条件,它会检查所选索引,因此它只会删除一项。

如果要删除所有选定的值,则需要使用JList中的方法,该方法返回多个要删除的值。 查看可用于此目的的其他getSelected...()方法的API。 然后,您将需要创建一个循环以删除所有值。

返回对象而不是索引值的方法将更易于使用,因为您可以从模型中删除对象,而不必担心首先删除较高的索引值。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM