我正在使用NetBeans Outline模型创建一个TreeTable,该技术被描述为here:
一切看起来都很干净,现在我想在我的模型中添加一个TreeModelListener来监听模型中的变化:
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
}
}
一切都按预期工作,但我的问题在下面,我编写了自己的TreeModel类,这显然意味着我必须编写自己的addTreeModelListener
方法,但我该怎么做?
public class MyTreeModel implements TreeModel {
private MyNode root;
public MyTreeModel(SdbNode root) {
this.root = root;
}
@Override
public void addTreeModelListener(TreeModelListener l) {
//TODO:
}
//...
}
答案 0 :(得分:1)
javax.swing.event.EventListenerList
将处理大部分繁重的工作。 add
,remove
和getListeners
方法的类参数允许您将所有侦听器存储在一个列表中,然后提取所需类型的子集。
注意:class参数是接口的类,而不是实现的类。
它基本上是这样的:
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);
}
如果您支持其余的模型通知,则需要针对调用treeNodesInserted
,treeNodesRemoved
或treeNodesChanged