Search code examples
javaswingjtabletooltiptablemodel

Getting JTable from its TableModel


I have a function which triggers with:

public void tableChanged(TableModelEvent e){...}

I got the TableModel from the TableModelEvent with:

TableModel model = (TableModel)e.getSource();

But I need the JTable to use it in a TablecellBalloonTip cosntructor. How can i get the JTable from the TableModel?


Solution

  • You cannot get it directly from the event. You installed the listener to the model, not the table itself. The model does not have a reference to the table. Actually, the same model could possibly be reused by several tables. So you have to store the reference to the table somewhere else. If you have only one table, then this should work:

    final JTable table = new JTable(); 
    table.getModel().addTableModelListener(new TableModelListener() {
      @Override   
      public void tableChanged(TableModelEvent e) {   
        table.doSomething();
      }
     });
    

    Otherwise, if you have more than one table, you can simply create a separate listener for each of them like above.