如何通知TreeModel其底层模型已更改?

时间:2013-02-26 20:23:24

标签: java swing model-view-controller jtree

我正在开发一个世界模拟,其中World表示为:

public class World {
    Turtle turtle;
    // .. basic constructors, getters, setters
}

Turtle表示为:

public class Turtle {
    List<Turtle> turtles;
    // .. basic constructors, getters, setters
}

其中Turtle位于其turtles的背面,World位于其中Turtle,主JTree tree = new JTree(new WorldModel(world.getTurtle()); public class WorldModel implements TreeModel { private Turtle = null; public WorldModel(Turtle turtle) { this.turtle = turtle; } @Override int getChildCount(Object object) { return ((Turtle) object).getNumTurtles(); } @Override Object getChild(Object parent, int index) { return ((Turtle) object).getTurtle(index); } // etc., you get the overbearing point } (可能在其下面有海龟)。我希望在Swing中将其表示为JTree。

所以我编写了一个JTree和一个TreeModel:

Turtle

这非常有效,直到我将{I}最初传入TreeModel的构造函数的world.getTurtle().removeAllTurtleChildren(); 更改为:

{{1}}

如何更新我的JList以反映此更改?我是否必须创建一个新的TreeModel并再次设置它?

(如果可能的话,我想远离DefaultTreeModel。)

1 个答案:

答案 0 :(得分:1)

添加支持将结构修改为模型的api:

public class WorldModel implements TreeModel {

     ...

     public void removeAllChildren(Turtle parent) {
         if (parent.getChildCount() == 0) return;
         Turtle[] children = parent.getChildren();
         int[] locations = new int[children.length());
         for(int loc = 0; loc < locations.length; loc++) {
            locations[i] = i;
         }
         parent.removeAllChildren();
         List<Turtle> path = new ArrayList<>();
         while (parent != null) {
             path.add(0, parent);
             parent = parent.getParent();
         }

         TreeModelEvent event = new TreeModelEvent(this, path, locations, children);
         // for each listener
              listener.treeNodesRemoved(event);   
     }
}

如您所见,这是相当有意义的工作 - 您可能会重新考虑不使用DefaultTreeModel :-)