简体   繁体   English

动态创建 Jtree

[英]Create Jtree dynamically

I'm struggling with creating a Jtree dynamically.我正在努力动态创建 Jtree。 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.我更喜欢属性,因为我希望能够从应用程序本身或通过手动编辑 *.properies 文件来更改它们。

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 String path) 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.使用平面层次结构(如String路径)将很难解析,因为您需要一些方法来查找先前创建的父节点并在它们不存在时创建路径。

Better to use something like XML or JSON, which can more easily describe hierarchy related data最好使用 XML 或 JSON 之类的东西,它们可以更轻松地描述与层次结构相关的数据

The following is an, overly simple, example of one way of approaching this, pay attention to the populate(DefaultMutableTreeNode parent, Item item) method以下是一个过于简单的示例,其中一种处理方法,请注意populate(DefaultMutableTreeNode parent, Item item)方法

在此处输入图像描述

Json...杰森...

[
   {
      "name":"Bowle",
      "contents":[
         {
            "name":"Apple",
            "contents":[
               
            ]
         },
         {
            "name":"Pear",
            "contents":[
               
            ]
         },
         {
            "name":"Orange",
            "contents":[
               
            ]
         }
      ]
   },
   {
      "name":"Freezer",
      "contents":[
         {
            "name":"Top draw",
            "contents":[
               {
                  "name":"Chicken",
                  "contents":[
                     
                  ]
               },
               {
                  "name":"Steak",
                  "contents":[
                     
                  ]
               },
               {
                  "name":"Fish",
                  "contents":[
                     
                  ]
               }
            ]
         },
         {
            "name":"Bottom draw",
            "contents":[
               {
                  "name":"Peas",
                  "contents":[
                     
                  ]
               },
               {
                  "name":"Chips",
                  "contents":[
                     
                  ]
               },
               {
                  "name":"Ice cream",
                  "contents":[
                     
                  ]
               }
            ]
         }
      ]
   }
]

Source...资源...

import com.google.gson.Gson;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.EventQueue;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;

public class Main {

    public static void main(String[] args) {
        new Main();
    }

    public Main() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try (InputStreamReader reader = new InputStreamReader(getClass().getResourceAsStream("/resources/ImportantStuff.json"))) {
                    Gson gson = new Gson();
                    Item[] items = gson.fromJson(reader, Item[].class);

                    DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("My stuff");
                    DefaultTreeModel model = new DefaultTreeModel(rootNode);

                    for (Item item : items) {
                        populate(rootNode, item);
                    }

                    JFrame frame = new JFrame();
                    frame.add(new MainPane(model));
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);

                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    public class MainPane extends JPanel {

        public MainPane(TreeModel model) {
            setLayout(new BorderLayout());
            JTree tree = new JTree(model);
            tree.setCellRenderer(new ItemTreeCellRenderer());
            tree.setShowsRootHandles(true);
            add(new JScrollPane(tree));
        }

    }

    public class ItemTreeCellRenderer extends DefaultTreeCellRenderer {
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
            if (value instanceof DefaultMutableTreeNode) {
                DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                Object userObject = node.getUserObject();
                if (userObject instanceof Item) {
                    Item item = (Item) userObject;
                    setText(item.getName());
                }
            }
            return this;
        }

    }

    protected void populate(DefaultMutableTreeNode parent, Item item) {
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(item);
        parent.add(node);

        for (Item child : item.getContents()) {
            populate(node, child);
        }
    }

    public class Item {
        private String name;
        private List<Item> contents;

        public Item(String name) {
            this.name = name;
            this.contents = new ArrayList<>(8);
        }

        public String getName() {
            return name;
        }

        public List<Item> getContents() {
            return contents;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM