【发布时间】:2013-01-29 21:05:25
【问题描述】:
首先我应该说我正在使用 netbeans,而且我对整个 java GUI 游戏还是新手。
所以,我的问题是我创建了自己的特定于我的项目的树结构,我现在想使用我的结构来构造 JTree。
我正在阅读有关 Jtree 的主题,据我了解,我需要在我的结构中实现 TreeModel 接口。我还读到的另一种方法是使用 DefaultMutableTreeNode,但我找不到任何使用它的示例对我来说很清楚。
现在我已经构建了整个树结构并填充了数据,并试图避免重建它。如何将我的树实现为 Jtree?
package models;
import java.util.ArrayList;
import java.util.List;
public class IngredientTree {
private Node root;
public IngredientTree(){
root = new Node();
}
public IngredientTree(Node rootData) {
root = rootData;
}
public void setRoot(Node n){
root = n;
}
public Node getRoot(){
return root;
}
public void addToTree(Ingredient i){
if(root.getData().getName()=="") // Then it must be the root
root.setData(i);
else
addToTree(root,i);
}
private void addToTree(Node n, Ingredient i){
if(isFirstAdd(n)) //Has no parent and no children
n.addChild(new Node(i,n));
else if(n.hasChildren()){ //Has parent and children
if(!inChildren(n,i)){
if(inNode(n,i))
n.addChild(new Node(i,n));
}
else{
for(Node child : n.getChildren()){
addToTree(child,i);
}
}
}
else{ //Has parent but no children
n.addChild(new Node(i,n));
}
}
private boolean isFirstAdd(Node n){
return(!n.hasParent() && !n.hasChildren());
}
private boolean inChildren(Node n,Ingredient i){
for(Node child : n.getChildren()){
if(inNode(child,i))
return true;
}
return false;
}
private boolean inNode(Node n,Ingredient i){
return(i.getStartIndex() > n.getData().getStartIndex() &&
i.getEndIndex() < n.getData().getEndIndex());
}
public int countIngredients(){
return countIngredients(this.getRoot());
}
private int countIngredients(Node r){
int count = 0;
if(!r.hasChildren()){
return 1;
}else{
for(Node child: r.getChildren()){
count += countIngredients(child);
}
}
return count;
}
}
【问题讨论】:
-
重建它!不这样做是一个陷阱。一开始似乎更容易,但现在你有一个适当的数据模型,你可以添加自己的逻辑。切换到摇摆模式实际上会退后一步。
-
我不知道您的全部要求,但为了创建一个简单的 JTree,您可以在此处 (apl.jhu.edu/~hall/java/Swing-Tutorial/Swing-Tutorial-JTree.html) 找到一个演示示例。由于您已经有了一个包含数据的结构,您可以将
processHierarchy方法“调整”到您自己的数据。 -
@flup 您是否建议实施树模型并基于该结构进行重建? @Ivo 谢谢!