为什么 addTreeModelListener() 不起作用?

Why is addTreeModelListener() not working?

以下代码导致没有监听器被添加到树(空列表)中:

CustomTreeModel model = (CustomTreeModel) jTree_ATree.getModel();
model.addTreeModelListener(new CustomTreeModelListener(jTree_ATree, CustomTreeModelListener.InsertionAction.EXPAND));

System.out.println("LISTENERS:");
for (CustomTreeModelListener listener : model.getListeners(CustomTreeModelListener.class)) {
    System.out.println(listener);
}

备注:

为什么没有将侦听器添加到 TreeModel?

监听器不是由它们的实际 class 存储的,而是由它们实现的监听器接口存储的。因此,要获得您的听众,请使用 model.getListeners(TreeModelListener.class)。这在DefaultTreeModel.getListener(...)的JavaDoc中也有解释:

Returns an array of all the objects currently registered as FooListeners upon this model. FooListeners are registered using the addFooListener method.

看一下DefaultTreeModel的源码也一目了然:

public void addTreeModelListener(TreeModelListener listener) 
{
    listenerList.add(TreeModelListener.class, listener);
}

public <T extends EventListener> T[] getListeners(Class<T> listenerType)
{
    return listenerList.getListeners(listenerType);
}