First off I should say that I am using netbeans and I am new to the whole java GUI game.
So, my problem is that I created my own Tree structure specific to my project and I now want to use my structure to construct the JTree.
I was reading up on the topic of Jtree and, from what I understand, I need to implement the TreeModel interface into my structure. The other way I also read about, was to use DefaultMutableTreeNode but I cannot find any examples using it that are clear to me.
Right now I have my entire tree structure constructed and filled with data and am trying to avoid reconstructing it. How can I implement my tree into a 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;
}
}
processHierarchy
method to your own data. – Ivo