I’m using the NetBeans Outline model to create a TreeTable, the technique is described here:
Everything looks nice and clean and I now want add a TreeModelListener to my model to listen for changes in the model:
Outline outline = new Outline();
MyNode root = new MyNode("data", 0);
//...
TreeModel treeMdl = new MyTreeModel(root);
OutlineModel mdl =
DefaultOutlineModel.createOutlineModel(treeMdl, new MyRowModel(), true, "Data");
mdl.addTreeModelListener(new MyTreeModelListener());
outline.setModel(mdl);
//...
public class MyTreeModelListener implements TreeModelListener {
public void treeNodesChanged(TreeModelEvent e) {
System.out.println("Something happend");
}
public void treeNodesInserted(TreeModelEvent e) {
// TODO Auto-generated method stub
}
public void treeNodesRemoved(TreeModelEvent e) {
// TODO Auto-generated method stub
}
public void treeStructureChanged(TreeModelEvent e) {
// TODO Auto-generated method stub
}
}
Everything works as expected, but my problem is below, I have written my own TreeModel class and that obviously means that I have to write my own addTreeModelListener method, but how do I do that?
public class MyTreeModel implements TreeModel {
private MyNode root;
public MyTreeModel(SdbNode root) {
this.root = root;
}
@Override
public void addTreeModelListener(TreeModelListener l) {
//TODO:
}
//...
}
The
javax.swing.event.EventListenerListwill handle most of the heavy lifting. The class parameter to theadd,remove, andgetListenersmethods allow you to store all of your listeners in one list, then extract a subset of only the type you want.Note: the class parameter is the class of the interface, not the class of the implementation.
It basically looks like this:
If you’re supporting the rest of the model notifications you’ll need to implement variations on the last method that call
treeNodesInserted,treeNodesRemoved, ortreeNodesChanged