JAVA – Remove Row from A JTable

How to remeve a row from a JTable.

This example illustrates how to remove a row from an existing JTable called table.
The row to be deleted will be the row that has been selected by clicking the mouse on it.

 

//CREATE MODEL INSTANCE FROM EXISTING TABLE
DefaultTableModel model = new DefaultTableModel();
model = (DefaultTableModel) table.getModel();

//DELETE THE SELECTED ROW
model.removeRow(table.getSelectedRow());
                
//INSERT A NEW EMPTY ROW
model.addRow(new Object[]{“”,””,””});

 

I used this with a confimation dialog, asking the user to confirm this is the correct row to be deleted;

int n = JOptionPane.showConfirmDialog(

null,

                “Are you sure you want delete – ” + table.getValueAt(table.getSelectedRow(), 2) + “?”,

                “”,

                JOptionPane.YES_NO_CANCEL_OPTION);          

           

//the user has clicked the cross

if(n == -1)

{

   return;

}

           

//the user has clicked cancel

if(n == 2)

{

   return;

}

 

//yes

if(n == 0){

   

    //CREATE MODEL INSTANCE FROM EXISTING TABLE

    DefaultTableModel model = new DefaultTableModel();

    model = (DefaultTableModel) table.getModel();

 

    //DELETE THE SELECTED ROW

    model.removeRow(table.getSelectedRow());

               

    //INSERT A NEW EMPTY ROW

    model.addRow(new Object[]{“”,””,””});

}

           

//no

if(n == 1){

    return;

}

Advertisements