생성 된 클론 인스턴스를 보여주는 동적 Jtree를 어떻게 구현할 수 있습니까?JTree of objects?
예를 들어 내 앱에서 새 책 (이름)을 만들 수 있습니다. 모든 책에서 chapter = ArrayList 수 있습니다. 그리고 지금 어떻게하면 jtree를 할 수 있습니까? JTree에 사용에 관련된
생성 된 클론 인스턴스를 보여주는 동적 Jtree를 어떻게 구현할 수 있습니까?JTree of objects?
예를 들어 내 앱에서 새 책 (이름)을 만들 수 있습니다. 모든 책에서 chapter = ArrayList 수 있습니다. 그리고 지금 어떻게하면 jtree를 할 수 있습니까? JTree에 사용에 관련된
클래스는 다음과 같습니다
JTree
클래스 자체 : 그들이 모델을 가지고!JTree
에 대한 데이터 컨테이너로 작동하는 DefaultTableModel implements TableModel
입니다. 루트 노드로 지정되면 모든 자식 노드가 루트 노드 또는 트리에 포함 된 다른 노드에 추가됩니다.DefaultMutableTreeNode
은 일반 JTree 노드의 범용 기본 구현입니다.이러한 것들을 어떻게 혼합합니까?
// 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
접근 당신은 또한 JTable
또는 JList
에 사용하는 것과 정말 동일합니다 : 우선 당신이 그것을 here에 대한 자바 태양 가이드를 확인하지만, 이런 식으로 뭔가를하는 것에 대한 생각할 수있는 빠른 모습을 가지고하는 것이 좋습니다 데이터 구조 (및 모델)가 다른 경우. 이것이 기본값 인 방법이라고 생각하면되지만, 실제로 필요한대로 TreeNode
또는 TreeModel
클래스를 쉽게 작성할 수 있습니다.
Java에 대한 Sun의 가이드에는 기본 JDK에 포함 된 거의 모든 항목이 포함되어 있으므로 잃어버린 느낌을주기 전에 살펴 보는 것이 좋습니다.
당신은 또한 자신의 모델을 구현할 수있다, 여기 내가 사용자의 그룹과 그룹을 위해 만든 하나의 이동 :
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;
}
}