gpt4 book ai didi

java - 实现树模型

转载 作者:行者123 更新时间:2023-11-30 05:52:31 31 4
gpt4 key购买 nike

我正在尝试编写一个实现 TreeModel 类的类。我希望有人能指导我朝着正确的方向前进。下面是我的课。问题是当我将它绑定(bind)到 jTree 组件时,第二级不断被添加。所以我怀疑我对父对象的引用是错误的:

public class PMEntry implements TreeModel{

private String title;
private List<PMEntry> pmEntryCollection;
private String pmId;
private String href;
private PMEntry root;
private ModuleType type;

public PMEntry (PMEntry root){

this.root = root;
}

@Override
public Object getRoot() {

return ((PMEntry)this.root);
}

@Override
public Object getChild(Object o, int i) {


if(getPmEntryCollection().isEmpty()){

return null;

}else {

return (PMEntry) getPmEntryCollection().get(i);

}
}

@Override
public int getChildCount(Object o) {

if(getPmEntryCollection().isEmpty()){

return 0;

}else {

return getPmEntryCollection().size();

}
}

@Override
public boolean isLeaf(Object o) {
PMEntry pmentry = (PMEntry)o;
return (pmentry.getType() == ModuleType.DM) ? true : false;
}

@Override
public void valueForPathChanged(TreePath tp, Object o) {
//todo
}

@Override
public int getIndexOfChild(Object parent, Object child) {

if (!(parent instanceof PMEntry)){

System.out.println("Returning -1");
return -1;
}

PMEntry pParent = (PMEntry) parent;

List<PMEntry> children = pParent.getPmEntryCollection();

if (children == null) {
System.out.println("children = null, Returning -1");
return -1;

}

for (int i = 0; i < children.size(); i++) {

System.out.println("Child:" + child);

if (children.get(i) == child) {

return i;
}

}

return -1;
}

@Override
public void addTreeModelListener(TreeModelListener tl) {
//todo
}

@Override
public void removeTreeModelListener(TreeModelListener tl) {
//todo
}

@Override
public String toString(){

return this.getTitle();
}
public enum ModuleType {

PM,
DM

}

// getters and setters here....

这是我如何绑定(bind)数据的片段

PMEntry tm = new PMEntry(null);
tm.setTitle("Root");

PMEntry pmRoot = new PMEntry((PMEntry)(tm));
pmRoot.setTitle("Project");

PMEntry pm1 = new PMEntry(pmRoot);
pm1.setType(PMEntry.ModuleType.DM);
pm1.setTitle("Publication Module");

PMEntry pm2 = new PMEntry(pmRoot);
pm2.setType(PMEntry.ModuleType.PM);
pm2.setTitle("Chapter");

List<PMEntry> pmCollection = new ArrayList<PMEntry>();
List<PMEntry> pmCollection1 = new ArrayList<PMEntry>();

PMEntry pm3 = new PMEntry(null);
pm3.setType(PMEntry.ModuleType.DM);
pm3.setTitle("Data Module");

PMEntry pm4 = new PMEntry(null);
pm4.setType(PMEntry.ModuleType.DM);
pm4.setTitle("Data Module");

pmCollection1.add(pm3);
pmCollection1.add(pm4);

pm2.setPmEntryCollection(pmCollection1);

pmCollection.add(pm1);
pmCollection.add(pm2);

pmRoot.setPmEntryCollection(pmCollection);

this.jTree1.setModel(pmRoot);

最佳答案

我想知道为什么您认为需要实现 TreeModel。您是否查看过 DefaultTreeModel?除了该类之外,您还计划实现哪些新行为?

关于java - 实现树模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11596888/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com