views:

88

answers:

1

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:
    }

    //...
}
A: 

The javax.swing.event.EventListenerList will handle most of the heavy lifting. The class parameter to the add, remove, and getListeners methods 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:

    private EventListenerList listeners = null;

    public void addTreeModelListener(TreeModelListener l) {
        if (l == null)
            return;
        if (listeners == null)
            listeners = new EventListenerList();
        listeners.add(TreeModelListener.class, l);
    }

    public void removeTreeModelListener(TreeModelListener l) {
        if (l == null)
            return;
        if (listeners == null)
            return;
        listeners.remove(TreeModelListener.class, l);
    }

    private void fireTreeStructureChanged(TreeModelEvent e) {
        if (e == null)
            return;
        if (listeners == null)
            return;
        TreeModelListener[] ll = listeners.getListeners(TreeModelListener.class);
        for(int i = 0; i < ll.length; i++)
            ll.treeStructureChanged(e);
    }

If you're supporting the rest of the model notifications you'll need to implement variations on the last method that call treeNodesInserted, treeNodesRemoved, or treeNodesChanged

Devon_C_Miller
Thank you! This should be it...
Ed Taylor