Search code examples
javaswingjtablelistener

How to add a table listener to a JTable?


I am having problems with fixing something in my program. Basically I know how to use action Listeners but there is no option to add one to a JTable. How is this done?

Basically I want to add an action Listener to my table so that every time a value is changed it will update that field in my data base.

I.E.

JTable.addActionListener (new ActionListener) {
    // text is changed
    updateDataBase();
};

Solution

  • You should add a listener to the TableModel:

    yourtableObject.getModel().addTableModelListener(new TableModelListener() {
    
      public void tableChanged(TableModelEvent e) {
         // your code goes here, whatever you want to do when something changes in the table
      }
    });
    

    TableModelEvent contains row and column number and type of modification.

    TableModelEvent is used to notify listeners that a table model has changed.