Hopefully a simple question but I am struggling with inheritance.
The ultimate goal is to detect when a cell is changed in a JTable and then run an action that involves getting an extra specific property associated with the table.
I have a class that extends JTable, so that I can add some extra properties to the table. The point of extending JTable is so that when a TableModelListener is activated I can get at the extra properties.
public class dataTable extends JTable implements TableModelListener{
private final PowerpointTable extraProperty;
public dataTable(String[][] tableArray, String[] colNames, PowerpointTable extraProperty) {
super(tableArray, colNames);
this.extraProperty= extraProperty;
}
public PowerpointTable getExtraProperty() {
return this.extraProperty;
}
}
I would then like to treat this class like a JTable and in another class create the table and add an table listener that fires when the cells are changed.
public secondClass {
public secondClass() {}
public void createTable() {
dataTable newdataTable= new dataTable(tableArray, columnNames, currentTable);
newdataTable.getModel().addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent tme) {
PowerpointTable pptT = tme.getSource().getExtraProperty;
});
}
however getSource only returns a JTable which cannot be cast to a dataTable.
Please let me know how I can access this property or if there is a better way to implement this functionality.
Solved it,
as rdonuk pointed out, getSource returns a TableModel,
I therefore changed the first class to extend a DefaultTableModel and added the extra property.
public class TryingTableModel extends DefaultTableModel {
public TryingTableModel(PowerpointTable pptRef, Object[][] os, Object[] os1) {
super(os, os1);
this.pptRef = pptRef;
}
private final PowerpointTable pptRef;
public PowerpointTable getPPTTable() {
return this.pptRef;
}
public String testAccess() {
return "it worked";
}
The JTable is now initialised in the second class
TryingTableModel tableModel = new TryingTableModel(currentTable, tableArray, columnNames);
tableModel.addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent tme) {
TryingTableModel tableModel = (TryingTableModel) tme.getSource();
System.out.println(tableModel.testAccess());
}
});
JTable newJTable = new JTable(tableModel);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.