1

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

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

aTurtle表示为:

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

一个Turtle站在它的背上,其余turtlesWorld靠在一个上,主要的Turtle(下面可能有乌龟)。我想在 Swing 中将其表示为 JTree。

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

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


}

在我更改Turtle最初传递给 TreeModel 的构造函数的点之前,这非常有效:

world.getTurtle().removeAllTurtleChildren();

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

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

4

1 回答 1

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

于 2013-02-27T09:58:34.530 回答