根据该线程中的评论,关于使用TreeViewer
和少量实验的 Eclipse 角文章之一我创建了一个工作模型。
以下是步骤:
创建如下监听器接口
public interface TreeModelListener extends EventListener {
public void onDelete(TreeObject obj);
}
让树内容提供者为每个树模型项添加侦听器并实现此接口,如下所示
public class TreeContentProvider implements IStructuredContentProvider,ITreeContentProvider,TreeModelListener {
TreeViewer tv;
public TreeContentProvider(TreeViewer tv){
this.tv=tv;
}
int cnt=0;
public void inputChanged(Viewer v, Object oldInput, Object newInput) {
cnt ++;
System.out.println("inputChanged() called "+oldInput+" new: "+newInput);
if(newInput!=null){
((TreeParent)newInput).setListener(this);
TreeObject []items = ((TreeParent)newInput).getChildren();
for(TreeObject obj : items){
if(obj instanceof TreeParent){
((TreeParent) obj).setListener(this);
}
}
}
}
....
@Override
public void onDelete(TreeObject obj) {
System.out.println("Delete of "+obj+" handled by content handler ");
TreeParent parent = obj.getParent();
if(parent.getChildren().length<=1){
return;
}
parent.removeChild(obj);
this.tv.refresh();
}
}
向TreeModel
类中添加一个方法,如下所示。显然,TreeParent
类应该有一个ArrayList
在上面#1 中使用的监听器
public void fireChildDelete(final TreeObject obj){
if(this.listener!=null){
new Runnable(){
@Override
public void run() {
System.out.println("New thread spawned with ID "+Thread.currentThread().getId());
listener.onDelete(obj);
}
}.run();
}
}
最后添加KeyListener
到TreeViewer
Object 以处理 Delete 键,如下所示:
tv.getTree().addKeyListener(new KeyListener(){
@Override
public void keyPressed(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
if(e.keyCode==SWT.F3){
System.out.println("F3 pressed... new element will be added");
TreeParent root = (TreeParent) tv.getInput();
TreeParent activityRoot = (TreeParent) root.getChildren()[0];
activityRoot.addChild(new TreeObject("NEW_ACTIVITY"));
//viewer.update(root, null);
tv.refresh();
}
if(e.keyCode==SWT.DEL){
System.out.println("DEL key pressed... element will be deleted "+((Tree)e.getSource()).getSelection().length);
if(((Tree)e.getSource()).getSelection().length>0){
final IStructuredSelection selection = (IStructuredSelection) tv
.getSelection();
System.out.println("DEL#2 key pressed... element will be deleted "+selection.getFirstElement().getClass());
TreeParent parent = ((TreeObject)selection.getFirstElement()).getParent();
parent.fireChildDelete((TreeObject) selection.getFirstElement());
//tv.remove(selection.getFirstElement());
//viewer.update(viewer.getInput(),null);
//tv.refresh();
}
}
}
});