Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove row from jtable

i want to remove a row from jtable in swing form enter image description here

Jtable >> dragged autmatically from Netbeans swing ( Netbeans 8 )

private javax.persistence.EntityManager entityManager;
private javax.swing.JButton jButton1;
private javax.swing.JButton jButton2;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private java.util.List<javaapplication1.Orders> ordersList;
private javax.persistence.Query ordersQuery;
private org.jdesktop.beansbinding.BindingGroup bindingGroup;

Jtable data >> bind auomatically from MySQL database

i want to delete the row from the jtable only not from the database

 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
    // TODO add your handling code here:

    int selectedRow =  jTable1.getSelectedRow();
    if(selectedRow!=-1)
    {
        try {
            jTable1.remove(selectedRow);
            jTable1.revalidate();
        } catch (Exception e) {
            e.getMessage();
        }

    }
} 
like image 651
Bassam AbdEltwab Avatar asked May 29 '26 20:05

Bassam AbdEltwab


1 Answers

At this line:

jTable1.remove(selectedRow);

This remove(int index) method doesn't do what you think it does. It is inherited from Container class and it is intended to remove components from a given container.

Instead of that you need to work with the TableModel and remove the selected row from it. Since you are using matisse (NetBeans' GUI Builder) then the table model attached to your table will be an instance of DefaultTableModel, so you can do as follows:

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    int viewIndex = jTable1.getSelectedRow();
    if(viewIndex != -1) {
        int modelIndex = jTable1.convertRowIndexToModel(viewIndex); // converts the row index in the view to the appropriate index in the model
        DefaultTableModel model = (DefaultTableModel)jTable1.getModel();
        model.removeRow(modelIndex);
    }
}

Please take a look to:

  • How to Use Tables
  • JTable#convertRowIndexToModel(int rowIndex)
  • DefaultTableModel#removeRow(int rowIndex)
like image 124
dic19 Avatar answered Jun 01 '26 09:06

dic19



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!