简体   繁体   中英

Logical error when trying to remove an item from a JList

I have a JList that shows all the items I have added to the database. When I want to remove multiple items, say two items, just one of them gets removed. This is my code: This method is from my class 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();
}

The class Controller:

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

and the class View. Used in the actionListener when the button remove is clicked.

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

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

Please consider that I'm new in this field with database programming. Thanks in advance.

When I want to remove multiple items, say two items, just one of them gets removed.

Your code only has an if condition that checks the selected index so it will only ever delete one item.

If you want to delete all selected values then you need to use a method from JList that returns multiple values to delete. Look at the API for other getSelected...() methods that you can use for this purpose. Then you will need to create a loop to delete all the values.

The method that return Objects istead of index values will be easier to use since you can just delete the Object from the model and you don't need to worry about deleting the higher indexed value first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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