Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Syntax
public void removeRow(int row)
Example
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);
table.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
button = new JButton("Remove");
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent ae) {
// check for selected row first
if(table.getSelectedRow() != -1) {
// remove selected row from the model
model.removeRow(table.getSelectedRow());
JOptionPane.showMessageDialog(null, "Selected row deleted successfully");
}
}
});
add(new JScrollPane(table), BorderLayout.CENTER);
add(button, BorderLayout.SOUTH);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new RemoveSelectedRowTest();
}
}
Output
Advertisements