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

2 thoughts on “JAVA – Remove Row from A JTable

    • Hi

      how are you loading the data into the JTable?

      This Method deletes the row from the JTable at runtime.

      You will need to pass the deletion back to your data store – for example a database, array or other data storage.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s