Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

JTable - tableChanged  RSS feed

David Shepherd
Ranch Hand
Posts: 35
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want to capture the adding of rows to a table. I am using a JTable with a custom table model extending DefaultTableModel. I am trying to use the tableChanged (TableModelEvent e) of the TableModelListener interface. I guess I am a little confused on where I put the implementation of this interface? How do I get the table to fire this event? I assume I add a listener to the table, or table model?
Thanks for the help.
Bryan Fagan
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can create a class that implements the TableModelListener. Once you create your table model, call the table model's addTableModelListener model and pass your TableModelListener as a parameter.
DefaultTableModel dfm = new DefaultTableModel();
You've just registered your TableModelListener with your TableModel. When the JTable fires a change event, your TableModelListener Class will be notified.
See code below.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.table.*;
public class Test extends JFrame {
private JTable jTable;
private JScrollPane jScroll;
private DefaultTableModel dfm;

private Object[] columnNames = {"Test","Test1","Test2", "Test3" };
public Test() {

getContentPane().setLayout(new BorderLayout());
dfm = new DefaultTableModel(columnNames,5);
dfm.addTableModelListener(new MyTableListener());
// add a new row.

jTable = new JTable(dfm);
jScroll = new JScrollPane(jTable);
getContentPane().add(jScroll, BorderLayout.CENTER);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {

public static void main(String[] args) {
Test tst = new Test();
class MyTableListener implements TableModelListener {
public void tableChanged(TableModelEvent te) {
if(te.INSERT == te.getType()) {
System.out.println("A new row was added.");
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!