views:

34

answers:

1
+1  Q: 

JTree of objects?

Hello, How I can implement dynamic Jtree, which shows created instances of clases?

For example, I can create new Book(name) in my app. In every book can be chapters = ArrayList of Chapter. And now How I can do a jtree from it?

A: 

Class involved in JTree usage are the following:

  • the JTree class itself which provides the displayable item you need and it works exactly like tables and lists in swing: they have a model!
  • the DefaultTableModel implements TableModel which works as a data container for a JTree. It is istantiated with a root node, then every children is added to root node or to other nodes contained in the tree.
  • the DefaultMutableTreeNode which is a general purpose default implementation for a generic JTree node.

How to mix up these things? First of all I suggest you to check java sun guide about it here but to have a quick look you can think about having something like this:

// this is the root of your tree
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Books");

for (Book b : books)
{
  // this adds every book to the root node
  DefaultMutableTreeNode curBook = new DefaultMutableTreeNode(b);

  root.add(curBook);

  // this adds every chapter to its own book
  for (Chapter c : b.chapters())
    curBook.add(new DefaultMutableTreeNode(c));
}

// at this point you have your tree ready, you just have to setup the model and create the effective JTree

DefaultTreeModel treeModel = new DefaultTreeModel(root);
JTree tree = new JTree(treeModel);

//now you tree is ready to be used

Approach is really identical to the one you use for JTable or JList also if data structure (and so model) differs. Think about that this is the default way to do it but you can easily write your own TreeNode or TreeModel class according to what you really need.

I would like to let you know that sun's guide about java contains almost every topic contained in the basic JDK so it's a good thing to give it a look before feeling lost.

Jack