user3731857
user3731857

Reputation: 23

Tree structure in Java?

I want to implement a tree structure. Each node in the tree contains an object of my choosing, and a link to each of each children, and possibly parents. I am wondering if something like this exists in Java, so for example:

T randomObject = new randomObject();
Node<T> root;
root.setObject(randomObject);
root.addChild( ... 
....
root.getFirstChild().getObject().getObjectProperty();

I have looked into Node structure (org.w3c.dom.Node), but it does not seem to be able to store objects and seems more for parsing a document.

I also looked into things like DefaultMutableTreeNode, MutableTreeNode, and TreeNode, but I have not been able to find clear examples of usage. I encounter a lot of problems with these. For example, when passing a DefaultMutableTreeNode as a parameter (does not seem to work), or when getting the child of a DefaultMutableTreeNode, which seems to return simply a TreeNode, when I clearly have added DefaultMutableTreeNode as a child.

I am new to Java so any information would be very helpful. The Oracle documentation is not that helpful. I have worked with the Vector structure, which is very easy to work with, can store objects and is easily accesible, and am wondering if something similar may exist. Thanks.

Upvotes: 0

Views: 302

Answers (2)

poshjosh
poshjosh

Reputation: 321

Check out https://github.com/poshjosh/bcuitreebuilder

A light weight java library for building TreeNodes from Documents, Files etc

public class ReadMe {

    public static void main(String [] args) {

        TreeBuilderFactory treeBuilderFactory = new TreeBuilderFactoryImpl();

        // For displaying each JTree
        //
        JScrollPane scrollPane  = new JScrollPane();
        scrollPane.setBounds(0, 0, 300, 300);

        // DocumentTreeBuilder 
        //
        Document doc = loadDocument(
             new File(System.getProperty("user.home")+"/Documents/Desktop/welcome.xml"));

        DOMTreeBuilder domTreeBuilder = treeBuilderFactory.getDOMInstance();

        Filter<Node> nodeFilter = null; // May be null

        TreeNode docRootNode = domTreeBuilder.build(doc, nodeFilter);

        JTree documentTree = new JTree(docRootNode);

        // Display the JTree
        //
        scrollPane.setViewportView(documentTree);
        JOptionPane.showMessageDialog(null, scrollPane);


        // FileTreeBuilder
        //
        File dir = new File(System.getProperty("user.home")+"/Documents");

        TreeBuilder<File> fileTreeBuilder = 
                 treeBuilderFactory.getInstance(TreeBuilderFactory.FILE);
        // This also works
        //FileTreeBuilder fileTreeBuilder = treeBuilderFactory..getFileInstance(); 

        Filter<File> fileFilter = new Filter<File>() {
            @Override
            public boolean accept(File f) {
                return f.isDirectory() || f.getName().endsWith(".docx");
            }
        };

        TreeNode fileRootNode = fileTreeBuilder.build(dir, fileFilter);

        JTree fileTree = new JTree(fileRootNode);

        // Display the JTree
        //
        scrollPane.setViewportView(fileTree);
        JOptionPane.showMessageDialog(null, scrollPane);


        // MapTreeBuilder
        //
        MapTreeBuilder mapTreeBuilder = treeBuilderFactory.getMapInstance();

        final HashMap map = new HashMap();
        map.put("boolean", Boolean.TRUE);
        map.put("number", 100);
        map.put("List", new String[]{"1", "2", "3"});
        HashMap grandChildren = new HashMap();
        grandChildren.put("grandChild", "I am a grand child");
        map.put("hasChildren", grandChildren);

        Map.Entry rootEntry = mapTreeBuilder.createRootEntry(map);

        TreeNode mapRootNode = mapTreeBuilder.build(rootEntry, null);

        JTree mapTree = new JTree(mapRootNode);

        // Display the JTree
        //
        scrollPane.setViewportView(mapTree);
        JOptionPane.showMessageDialog(null, scrollPane);
    }

    private static Document loadDocument(File file) {
        Document doc;
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder docBuilder = factory.newDocumentBuilder();
            doc = docBuilder.parse(file);
        }catch (SAXException | IOException | ParserConfigurationException e) {
            e.printStackTrace();
            doc = null;
        }
        return doc;
    }
}

Upvotes: 1

Shashank
Shashank

Reputation: 133

I wanted something similar a few days back. This is what I did:

public class MyTreeNode extends DefaultMutableTree{
  //add all your objects here
}

DefaultMutableTree has predefined methods like add() -> to add child, it uses enumeration and provides standard methods to access child nodes using preorder and postorder processing.

Upvotes: 0

Related Questions