I'm struggling with creating a Jtree dynamically. What I have in mind is to store the string for nodes in properties file and loop through them, adding the Default mutable tree nodes to the root node. I prefer Properties, because I'd like to be able to change them from the app itself or by editing the *.properies file manually.
I want to create a model with parents and children (sometimes two children). I've managed to create nodes, but can't figure out how can it be done, so there would be parents and children, so I would set which nodes would be children to specific parent nodes. That is what I have for now, plus a properties file with couple of keys and properties, in which I store the node strings:
DefaultMutableTreeNode allnodes = new DefaultMutableTreeNode("", true);
DefaultMutableTreeNode elements = new DefaultMutableTreeNode("Elements", true);
Set<String> keys = Prop1.stringPropertyNames();
for (String key : keys) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(Prop1.getProperty(key), false);
elements.add(node);
}
allnodes.add(elements);
tree1 = new JTree(allnodes);
The problem is that this can only produce children or parent, based on what boolean I put creating it with:
DefaultMutableTreeNode node = new DefaultMutableTreeNode(Prop1.getProperty(key), false);
Can anyone tell me if that's possible and if it is, how can I accomplish it. Also I've read similar questions and answers everywhere and I couldn't find something that fits my needs. I would greatly appreciate any help I could get. Peter
The problem is, you need some way to describe your hierarchy. Using a flat hierarchy (like a
Stringpath) will be very hard to parse, as you will need some way to look up previously created parent nodes and create the paths when they don't exist.Better to use something like XML or JSON, which can more easily describe hierarchy related data
The following is an, overly simple, example of one way of approaching this, pay attention to the
populate(DefaultMutableTreeNode parent, Item item)methodJson...
Source...