Operation sur JTree

Résolu
alonsyl Messages postés 348 Date d'inscription mardi 6 avril 2004 Statut Membre Dernière intervention 6 novembre 2008 - 27 mars 2006 à 10:51
cs_zazou1 Messages postés 48 Date d'inscription mardi 28 décembre 2004 Statut Membre Dernière intervention 23 juillet 2010 - 28 mars 2006 à 00:27
bonjour,

dans le constructeur d'une JFrame, j'ai construis un JTree de la maniere suivante :

DefaultMutableTreeNode code6 = new DefaultMutableTreeNode("UUU") ;
DefaultMutableTreeNode code5 = new DefaultMutableTreeNode("YYY") ;
DefaultMutableTreeNode code4 = new DefaultMutableTreeNode("TTT") ;
DefaultMutableTreeNode code3 = new DefaultMutableTreeNode("RRR") ;

DefaultMutableTreeNode code2 = new DefaultMutableTreeNode("EEE") ;
DefaultMutableTreeNode code1 = new DefaultMutableTreeNode("ZZZ") ;
code2.add(code6);
code2.add(code5);
code1.add(code4);
code1.add(code3);
DefaultMutableTreeNode racine = new DefaultMutableTreeNode("AAA") ;
racine.add(code2);
racine.add(code1);
JTree monArbre = new JTree(racine) ;<?xml:namespace prefix o ns "urn:schemas-microsoft-com:office:office" />

le truc, c'est qu'il faudrait que mon utilisateur puisse (en cliquant sur un JButton) ajouter un noeud fils au noeud dont il aura specifie la designation dans un JTextField ("TTT" par exemple).
comment puis-je retrouve par le code un reference sur le noeud dont la designation est "XXX" ?

existe t'il un truc du genre :
"DefaultMutableTreeNode monNoeud = (DefaultMutableTreeNode) noeud_de_'monArbre'_dont_la_designation_est_"XXX";" ?

sinon, comment specifier une boucle du genre "pour chaque noeud de 'monArbre' => je verifie si la designation == "XXX"" ?

merci a vous,

alonsyl

4 réponses

Twinuts Messages postés 5375 Date d'inscription dimanche 4 mai 2003 Statut Modérateur Dernière intervention 14 juin 2023 111
27 mars 2006 à 14:44
Salut,



tu peux faire une recherche dans le jtree pas son chemin





exemple :



public TreePath findByName(String[] names) {

TreeNode root = (TreeNode) treeModel.getRoot();

return find(new TreePath(root), names, 0, true);

}





private TreePath find(TreePath parent, Object[] nodes, int depth,

boolean byName) {

TreeNode node = (TreeNode) parent.getLastPathComponent();

Object o = node;

// If by name, convert node to a string

if (byName)

o = o.toString();



// If equal, go down the branch

if (o.equals(nodes[depth])) {

// If at end, return match

if (depth == nodes.length - 1)

return parent;



// Traverse children

if (node.getChildCount() >= 0)


for (Enumeration e = node.children();
e.hasMoreElements();) {


TreeNode n = (TreeNode)
e.nextElement();


TreePath path =
parent.pathByAddingChild(n);


TreePath result = find(path,
nodes, depth + 1, byName);

// Found a match

if (result != null)

return result;

}

}

// No match at this branch

return null;

}





et a l'utilisation tu fais



TreePath path1 = tree.findByName(new String[] { root, node1 });

TreePath path2 = tree.findByName(new String[] { root, node1, node2, node3 });


WORA
3
cs_zazou1 Messages postés 48 Date d'inscription mardi 28 décembre 2004 Statut Membre Dernière intervention 23 juillet 2010
28 mars 2006 à 00:27
Réponse acceptée !
voila un bon code :
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;


public class Tree
{ public static void main (String [] args)
{

System.setProperty("Quaqua.tabLayoutPolicy","wrap");



// set the Quaqua Look and Feel in the UIManager
try {
UIManager.setLookAndFeel("ch.randelshofer.quaqua.QuaquaLookAndFeel");
// set UI manager properties here that affect Quaqua

} catch (Exception e) {
// take an appropriate action here

}
// insert your application initialization code here





JFrame frame =new SimpleTreeFrame();
frame.show();
}
}


class SimpleTreeFrame extends JFrame implements ActionListener
{ public SimpleTreeFrame()
{ setTitle("Simple Tree");
setSize(300,200);
addWindowListener (new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{ System.exit(0);
}
} );
// construit l' arbre
TreeNode root = makeSampleTree();
model = new DefaultTreeModel (root);
tree = new JTree (model);
tree.setEditable(true);


// ajoute un panneau deroulant contenant un arbre
Container contentPane = getContentPane();
contentPane.add(new JScrollPane(tree),"Center") ;


// cree les boutons du panneau
JPanel panel = new JPanel();
addSiblingButton = new JButton ("Ajouter un frere");
addSiblingButton.addActionListener (this);
panel.add(addSiblingButton);
addChildButton = new JButton ("Ajouter un enfant");
addChildButton.addActionListener (this);
panel.add(addChildButton);
deleteButton = new JButton ("Supprimer");
deleteButton.addActionListener (this);
panel.add(deleteButton);
contentPane.add ( panel , "South");
}


public TreeNode makeSampleTree()
{
// la definition des donnees du modele d' arbre
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Monde");
DefaultMutableTreeNode country = new DefaultMutableTreeNode("USA");
root.add(country);
DefaultMutableTreeNode state = new DefaultMutableTreeNode("Californie");
country.add(state);
DefaultMutableTreeNode city = new DefaultMutableTreeNode("San Jose");
state.add(city);
city = new DefaultMutableTreeNode("Cupertino");
state.add(city);
city = new DefaultMutableTreeNode("Michigan");
state.add(city);
city = new DefaultMutableTreeNode("Ann Arbor");
state.add(city);
country = new DefaultMutableTreeNode("Allemagne");
root.add(country);
state = new DefaultMutableTreeNode("Schleswig-Holstein");
country.add(state);
city = new DefaultMutableTreeNode("Kiel");
state.add(city);
return root ;
}
public void actionPerformed(ActionEvent event )
{
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) tree.getLastSelectedPathComponent();
if( selectedNode == null) return;
if( event.getSource().equals(deleteButton)) {
if (selectedNode.getParent() != null)
{ model.removeNodeFromParent(selectedNode);
return;
}
}
// add new node as sil
DefaultMutableTreeNode newNode = new DefaultMutableTreeNode("Nouveau");
if (event.getSource().equals ( addSiblingButton))
{ DefaultMutableTreeNode parent = (DefaultMutableTreeNode) selectedNode.getParent();
if(parent != null)
{ int selectedIndex = parent.getIndex(selectedNode);
model.insertNodeInto (newNode,parent, selectedIndex+1);
}
}
else if(event.getSource().equals(addChildButton))
{ model.insertNodeInto (newNode,selectedNode,selectedNode.getChildCount());
}
TreeNode[] nodes = model.getPathToRoot(newNode);
TreePath path = new TreePath(nodes);
tree.scrollPathToVisible(path);
}
private DefaultTreeModel model;
private JTree tree;
private JButton addChildButton,addSiblingButton, deleteButton,editButton;
}
3
bloofi Messages postés 388 Date d'inscription mercredi 1 octobre 2003 Statut Membre Dernière intervention 3 mai 2006 2
27 mars 2006 à 11:29
Coucou,



tu peux aussi ,en meme temps que tu construis ton arbre, stocker dans une hashmap les node avec pour cles leur id/nom :



hash.put("UUU" , new DefaultMutableTreeNode("UUU") );

etc...

apres tu peux facilement récupérer les node en fonction de leur id,
leur ajouter des fils, tout ca tout ca.... par contre c'est peut-etre
lourd a gérer.
0
alonsyl Messages postés 348 Date d'inscription mardi 6 avril 2004 Statut Membre Dernière intervention 6 novembre 2008 12
27 mars 2006 à 12:13
oui, j'avais bien pensais a cela mais j'ai alors l'impression de stocker +ieurs fois la meme info : 1 fois dans le JTree et 1 fois dans le hashmap ...

enfin, pour l'instant et faute de mieux, j'etais justement en train de realiser ce prg via 1 ArrayList de mes noeuds ;-)

merci a toi,

alonsyl
0
Rejoignez-nous