0

I have a JTable, which is a DefaultTableModel. The data in the table is accessed from the ArrayList CarList. The problem I am having, is that after I delete the row, it is only deleted temporarily. To delete the row in the project, the user has to select a row and then press the button delete. When I use the coding that I am using, the row is deleted from the jTable, but the data is not removed from my Arraylist, so when I open up the JTable again, the row that I deleted is still there. Can anyone please help me? I have some coding here :

 ArrayList CarList = CarRentalSystem.CarList;
 UsingFiles CarFile = CarRentalSystem.CarFile; //ArrayLists accessed from the whole project

/**
 * Creates new form ViewCars
 */
public ViewCars() { //creating the table and accessing the data from the arraylists
    initComponents();
    this.CarList=CarList;
    DefaultTableModel model = (DefaultTableModel) carTable.getModel();
    for (int i=0; i<CarList.size(); i++){
        Car car = (Car) CarList.get(i);
        model.addRow(new Object[]{car.getCarNum(), car.getManufacturer(), car.getModel(), car.getBooked(), car.getAircondition()});

    btnEdit.setVisible(true);
    btnDelete.setVisible(false);
    btnSave.setVisible(false);
    }

//delete button coding

     private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {                                          

        DefaultTableModel model = (DefaultTableModel) this.carTable.getModel();
        int[] rows = carTable.getSelectedRows();
        for(int i=0;i<rows.length;i++){
            model.removeRow(rows[i]-i);

            JOptionPane.showMessageDialog(null, "Row Deleted"); //the row is deleted but the data isn't

            }
}
}                  
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

0

Each time you create the JTable model you are taking all of item in your car list. You delete them from the table model, but you never remove the items from your array list. You need to modify your deletion code to remove from the carList.

You should also be naming your variables using lower camel case conventions.

  • I would create your own table model that contains the car list so that the table model itself can directly remove things from the car list. Unless you have use cases for the car list not being in sync with what you display in your JTable.
Dodd10x
  • 3,344
  • 1
  • 18
  • 27
0

Here you are failing to remove the items from ArrayList, therefore every time you create the JTable model all the items from CarList are added to JTable.

You need to add

CarList.remove(Object_To_Remove);

to your delete code.

For more help on how to delete objects from ArrayList see this. Remove Item from ArrayList this question on StackOverflow may help you. Or better way you can directly go for Docs.

Community
  • 1
  • 1
ravibagul91
  • 20,072
  • 5
  • 36
  • 59