How can we remove a selected row from a JTable in Java?

A JTable is a subclass of JComponent class for displaying complex data structures. A JTable component can follow the Model View Controller (MVC) design pattern for displaying the data in rows and columns. A JTable can generate TableModelListener, TableColumnModelListener, ListSelectionListener, CellEditorListener and RowSorterListener interfaces. We can remove a selected row from a JTable using the removeRow() method of the DefaultTableModel class.


public void removeRow(int row)


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
public class RemoveSelectedRowTest extends JFrame {
   private JTable table;
   private DefaultTableModel model;
   private Object[][] data;
   private String[] columnNames;
   private JButton button;
   public RemoveSelectedRowTest() {
      setTitle("RemoveSelectedRow Test");
      data = new Object[][] {{"101", "Ramesh"}, {"102", "Adithya"}, {"103", "Jai"}, {"104", "Sai"}};
      columnNames = new String[] {"ID", "Name"};
      model = new DefaultTableModel(data, columnNames);
      table = new JTable(model);
      button = new JButton("Remove");
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            // check for selected row first
            if(table.getSelectedRow() != -1) {
               // remove selected row from the model
               JOptionPane.showMessageDialog(null, "Selected row deleted successfully");
      add(new JScrollPane(table), BorderLayout.CENTER);
      add(button, BorderLayout.SOUTH);
      setSize(400, 300);
   public static void main(String args[]) {
      new RemoveSelectedRowTest();


Updated on: 02-Jul-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started