user3223721
user3223721

Reputation: 1

Mulitiple delete record from jtable through id which is link to database

My question: How to allow user to perform multiple delete from jtable through button.The table is
linked to my database.I have created a table model in another class and link to my SalesReceiptTable. I am able to delete one row from both the db and table when the user click the delete button. Should i do looping for the rowSelected ??

    //Button to perform delete
    JButton btnDelete = new JButton("Delete");
btnDelete.setFont(new Font("Tahoma", Font.PLAIN, 13));
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
    int rowSelected=SalesReceiptTable.getSelectedRow();
if(rowSelected>=0)
{
String id = SalesReceiptTable.getValueAt(rowSelected, 7).toString();
SalesReceipt1 e1=new SalesReceipt1(Integer.parseInt(id));
    e1.deleteSalesReceipt();
ArrayList<SalesReceipt1> result= SalesReceipt1.retrieveAllSalesReceipt();
SalesReceiptTableModel model= new SalesReceiptTableModel(result);
SalesReceiptTable.setModel(model);
    }
else{
JOptionPane.showMessageDialog(null,"No record selected","Alert", JOptionPane.ERROR_MESSAGE);
    }

    //My sql statement in my entity class
    public boolean deleteSalesReceipt(){
boolean success = false;
DBController db = new DBController();
    String dbQuery; 
db.getConnection();
    dbQuery = "DELETE FROM SalesReceipt WHERE salesReceiptId ='" + salesReceiptId +"'"; 
    if (db.updateRequest(dbQuery) == 1){
success = true;
                               }
    db.terminate();
    return success;
}

Upvotes: 0

Views: 143

Answers (1)

trashgod
trashgod

Reputation: 205775

Several approaches are possible:

  • Specify ListSelectionModel.MULTIPLE_INTERVAL_SELECTION in the table's setSelectionMode() method, as shown here, and examine the result returned by getSelectedRows().

  • Add a column of check boxes, as shown here, and enable the Delete button only when any are selected.

In all cases,

  • Convert between view and model row indices, as discussed here and here.

  • Consider supporting undo using a List<Row> to cache rows deleted from the model but not yet deleted from the database.

Upvotes: 2

Related Questions