Roman Rdgz
Roman Rdgz

Reputation: 13294

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?

Upvotes: 1

Views: 5672

Answers (2)

Ilya Boyandin
Ilya Boyandin

Reputation: 3099

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.

Upvotes: 5

Adeel Ansari
Adeel Ansari

Reputation: 39907

You need to keep the JTable instance somewhere, for later use. May be as a panel instance variable.

In MVC, the Model is not tied to a particular view or controller, hence you can not get it from the Model -- it is something very much expected.

Upvotes: 1

Related Questions