This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Swing / AWT / SWT and the fly likes JTable - tableChanged Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "JTable - tableChanged" Watch "JTable - tableChanged" New topic
Author

JTable - tableChanged

David Shepherd
Ranch Hand

Joined: Mar 02, 2001
Posts: 35
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
Greenhorn

Joined: Feb 26, 2001
Posts: 17
David:
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();
dfm.addTableModelListener(MyTableListener());
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.
dfm.addRow(columnNames);

jTable = new JTable(dfm);
jScroll = new JScrollPane(jTable);
getContentPane().add(jScroll, BorderLayout.CENTER);
setSize(400,200);
setVisible(true);
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});

}
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.");
}
}
}
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: JTable - tableChanged
 
Similar Threads
JTable - Adding Row
Refresh JTable
JTable
JTable
Jtable