Reputation: 687
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?
Upvotes: 3
Views: 5935
Reputation: 3621
You can also implement your own Model, here it goes one I made for Group and Group of Users:
public class GrupoUserTreeModel implements TreeModel
{
private String raiz;
private ArrayList<Grupo> grupos = new ArrayList<Grupo>();
private List<TreeModelListener> listeners = new ArrayList<TreeModelListener>();
public GrupoUserTreeModel(String raiz)
{
this.raiz = raiz;
}
public Object getRoot()
{
return raiz;
}
private void fireTreeStructureChanged()
{
Object[] o = {raiz};
TreeModelEvent e = new TreeModelEvent(this, o);
for(TreeModelListener l : listeners)
l.treeStructureChanged(e);
}
public void addGrupo(Grupo grupo)
{
grupos.add(grupo);
fireTreeStructureChanged();
}
public void addUsuario(Grupo grupo, Usuario usuario)
{
Grupo g = grupos.get(grupos.indexOf(grupo));
g.getUsuarios().add(usuario);
TreePath p = new TreePath(new Object[]{g});
this.fireTreeStructureChanged();
}
public void limpar()
{
grupos.clear();
this.fireTreeStructureChanged();
}
public void removeGrupo(Grupo grupo)
{
if(!grupos.remove(grupo))
throw new NullPointerException("Grupo: "+grupo+" inexistente na Tree");
this.fireTreeStructureChanged();
}
public ArrayList<Grupo> getGrupos()
{
return this.grupos;
}
public void setGrupos(ArrayList<Grupo> grupos)
{
this.grupos = grupos;
this.fireTreeStructureChanged();
}
public ArrayList<Usuario> getUsuarios(Grupo grupo)
{
Grupo g = grupos.get(grupos.indexOf(grupo));
return g.getUsuarios();
}
public void removeUsuario(Grupo grupo, Usuario usuario)
{
Grupo g = grupos.get(grupos.indexOf(grupo));
if(!(g.getUsuarios()).remove(usuario))
throw new NullPointerException("Usuário: "+usuario+" inexistente no Grupo: "+
grupo+" na Tree");
TreePath p = new TreePath(new Object[]{g});
this.fireTreeStructureChanged();
}
public Object getChild(Object parent, int index)
{
if(parent == raiz)
{
return grupos.get(index);
}
if(parent instanceof Grupo)
{
Grupo g = grupos.get(grupos.indexOf(parent));
return g.getUsuarios().get(index);
}
throw new IllegalArgumentException("Parent não é de um tipo suportado pela Tree");
}
public int getChildCount(Object parent)
{
if(parent == raiz)
return grupos.size();
if(parent instanceof Grupo)
{
Grupo g = grupos.get(grupos.indexOf(parent));
return g.getUsuarios().size();
}
throw new IllegalArgumentException("Parent não é de um tipo suportado pela Tree");
}
public boolean isLeaf(Object node)
{
return node instanceof Usuario;
}
public void valueForPathChanged(TreePath path, Object newValue)
{
}
public int getIndexOfChild(Object parent, Object child)
{
if(parent == raiz)
return grupos.indexOf(child);
if(parent instanceof Grupo)
return grupos.get(grupos.indexOf(child)).getUsuarios().size();
return 0;
}
public void addTreeModelListener(TreeModelListener l)
{
listeners.add(l);
}
public void removeTreeModelListener(TreeModelListener l)
{
listeners.remove(l);
}
}
public class Grupo
{
private ArrayList<Usuario> usuarios = new ArrayList<Usuario>();
private String nome;
public Grupo(String nome)
{
this.nome = nome;
}
/**
* @return the usuarios
*/
public ArrayList<Usuario> getUsuarios() {
return usuarios;
}
/**
* @param usuarios the usuarios to set
*/
public void setUsuarios(ArrayList<Usuario> usuarios) {
this.usuarios = usuarios;
}
/**
* @return the nome
*/
public String getNome() {
return nome;
}
/**
* @param nome the nome to set
*/
public void setNome(String nome) {
this.nome = nome;
}
public String toString()
{
return this.nome;
}
public boolean equals(Object outro)
{
if(outro instanceof Grupo)
{
Grupo o = (Grupo) outro;
return o.getNome().equals(this.getNome());
}
return false;
}
}
public class Usuario
{
private String nome;
public Usuario(String nome)
{
this.nome = nome;
}
/**
* @return the nome
*/
public String getNome() {
return nome;
}
/**
* @param nome the nome to set
*/
public void setNome(String nome) {
this.nome = nome;
}
public String toString()
{
return this.nome;
}
public boolean equals(Object outro)
{
if(outro instanceof Usuario)
{
Usuario o = (Usuario) outro;
return o.getNome().equals(this.getNome());
}
return false;
}
}
Upvotes: 1
Reputation: 133619
Class involved in JTree usage are the following:
JTree
class itself which provides the displayable item you need and it works exactly like tables and lists in swing: they have a model!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.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.
Upvotes: 2