Jtree level!

i have a jtree, and i want to show some data depending on the level of the tree, for example when i am on level 4 i want to show a comment or when i am on level 2 i want get some data from the database, the issue is the getLevel() function Returns the number of levels above this node(current node) -- the distance from the root to this node. If this node is the root, returns 0. so i end up getting the current level - 1.
how can i get the exact level for a certain node.
thanks

TreeModel consistes of TreeNode interface implementations. The interface has getParent() method. For root node the parent is null. SO to get level you can count how many times you move to parent.
If on the JTree you have row index ot selection. You can get TreePath by getSelectionPath() or getPathForRow() methods and count the path length by getPath() method (size of the array).
Regards,
Stas

Similar Messages

  • How to Use different icons for JTree in the same level

    Hi guys, i come cross a problem with JTree. The module need a JTree which need to represent items in the same level using different icons. For example:
    [Icon for Root]Root
    |
    |_____________[Icon for Table] TABLES
    |
    |_____________[Icon for Index] INDEXS
    |
    |_____________[Icon for Views] VIEWS
    As i know, the default behavior for JTree is using the same icon for all leaves and
    the same icon for all node that has children. How can i achieve that?
    Thansk a lot!

    subclass DefaultTreeCellRenderer. if you overwrite the method below, then you can set the icon to whatever you want....!
        public Component getTreeCellRendererComponent(JTree tree, Object value,
                                    boolean sel,
                                    boolean expanded,
                                    boolean leaf, int row,
                                    boolean hasFocus) {
         String         stringValue = tree.convertValueToText(value, sel,
                               expanded, leaf, row, hasFocus);
            this.tree = tree;
         this.hasFocus = hasFocus;
         setText(stringValue);
         if(sel)
             setForeground(getTextSelectionColor());
         else
             setForeground(getTextNonSelectionColor());
         // There needs to be a way to specify disabled icons.
         if (!tree.isEnabled()) {
             setEnabled(false);
             if (leaf) {
              setDisabledIcon(getLeafIcon());
             } else if (expanded) {
              setDisabledIcon(getOpenIcon());
             } else {
              setDisabledIcon(getClosedIcon());
         else {
             setEnabled(true);
             if (leaf) {
              setIcon(getLeafIcon());
             } else if (expanded) {
              setIcon(getOpenIcon());
             } else {
              setIcon(getClosedIcon());
            setComponentOrientation(tree.getComponentOrientation());
         selected = sel;
         return this;
        }

  • Jtree multiple level

    Impossible to link level coming from different rowset even the link is done at entity (by association) and view (by viewlink) level. The application module works fine with the link too. I cannot give the parameters into the setnodedefinitions correctly ...
    Note that i don't have any primary/foreign key because entity view are oracle database view that contains function (to_char(attribure,'YYYY')) because these are not supported into bc4j view object or bc4j entity.
    Association and view link has been created manually but are working fine in testing mode from the application module. Note that i have to put parenthesis in the where clause into the query in the view link (without jdev3 return Sql not properly ended, tar 143558.260).
    Both views are instantied into the class as rowset. Who as a full and good running example of a hierarchy into Jtree with vo without primary / foreign key. In my case i would have a hierarchy with year / quarter and finally the list of bills corresponding (very simple thing).
    I just need to set the parameters of the setnodedefinitions methods from Jtree but it was impossible until yet
    Thanks

    Hi
    Sounds like you having as much 'fun' as I am with the BE3K. I have a solution for you but may not be suitable in all cases.
    I needed to broadcast to 2 users and if they don't answer broadcast to everyone....this is how I got it working.
    Main number rings in to pilot (8900) which broadcasts to 2 users and I then placed a forward if no extensions are available
    to a user 8001. Note this user is not an actual user of the system. The user (8001) I set a call forward all to 8990 - a second hunt list. This hunt list has everyone else in as a broadcast group.
    Not ideal I know and uses a license just to get a basic hunt list working. Hope this helps you out.

  • How to load second level nodes dynamically in jTree?

    Hi,
    I'm new to jTree & I want to load jTree with two levels of Hierarchy dynamically.
    First level nodes I loaded from the database directly.
    And regarding the second level nodes, I want them to be loaded only when I expand the first level nodes(on tree expansion), instead of loading it before-hand itself.
    I tried this in TreeExpansion event, but still my tree was not refreshed.
    Is there anyother way to do this .....?
    Thanks.
    G.

    Hi sangar;
    use method valueChanged() in ListSelectionEvent interface to notify tree selection change.

  • JTree: HOW TO add a new node

    Hi everybody,
    Im going to try to be clear...
    My problem is the following: I am a beginner using JTree and what I want to do is to add a new node in a certain position in my JTree. I would be very grateful if apart from explanation, any of you could provide me with a piece of code.
    Let us think that my tree has the root and some first-level children called group 1, ..., group n. Every group has some children called rulemodule 1, ..., rulemodule m. And every rulemodule has some children called rule 1, ..., rule j.
    An example of the visual look of my jtree:
    root
    __ group 1
    ____ rulemodule 1.1
    ______ rule 1.1.1
    ____ rulemodule 1.2
    ______ rule 1.2.1
    ______ rule 1.2.2
    ______ rule 1.2.3
    __ group 2
    ____ rulemodule 2.1
    ______ rule 2.1.1
    ____ rulemodule 2.2
    ______ rule 2.2.1
    Then, let us say that what I want is to add a new rule in the position where it is in this moment rule 1.2.2 (so the rule that was 1.2.2 before would be now 1.2.3, and the one that was 1.2.3 would be now 1.2.4). So I know the name of the group, the name of the rulemodule and the position of the new rule. How could I do that?
    In order to build the JTree I have the following statements:
    TreeNode treeNode = fillTheTree(ruleModulePart.config.getRuleModules()); This function actually builds the tree.
    jTreeModel = new DefaultTreeModel(treeNode);
    jTree = new JTree(jTreeModel);
    Thanks a lot to everybody!
    Fran.

    Thanks a lot for your answer Maxideon,
    Well, I think that I did not explained it the problem very well...
    The example of the tree was just that, an example, but the tree does not look like that. I just wanted to show that the tree has 3 levels of depth.
    The declaration of the function would actually be like that:
    public void UpdateJTreeWithNewRule (String groupName, String ruleModuleName, String newRuleName, int positionOfNewRule) {
    }So I think that I would need to do first a search to find the position of the "group" which corresponds to that 'groupName' and after that the position of the "rulemodule" which corresponds to that 'ruleModuleName'. And then add the 'newRuleName' in the position 'positionOfNewRule' inside that "rulemodule".
    Thanks a lot again,
    Fran.

  • How to show only all children of selected node in JTree??

    Dear friends:
    I have Two Panels, PA and PB,
    PA has a Jtree as code below, and PB listens to PA,
    I hope to do following,
    If I select a node called A in PA, then Node A's all children such as A1, A2, A3 will be displayed in PB, but not display A1, A2, A3's children such as A3 has C1, C2, C3, C4 & C5, until I select A3 then PB will display only all A3's children: C1, C2, C3, C4 & C5;
    i.e, only populate each ONE level of children of Node A or any node I select, not its grandchildren and its grand-grand children;
    Please help how to do it??
    I tried amny times, failed.
    Thanks
    [1]. PA panel code:
    package com.atest;
         import java.awt.BorderLayout;
         import java.awt.event.MouseAdapter;
         import java.awt.event.MouseEvent;
         import java.util.Enumeration;
         import java.awt.Dimension;
         import javax.swing.JFrame;
         import javax.swing.JPanel;
         import javax.swing.JScrollPane;
         import javax.swing.JTextField;
         import javax.swing.JTree;
         import javax.swing.tree.DefaultMutableTreeNode;
         import javax.swing.tree.TreeModel;
         import javax.swing.tree.TreePath;
         public class DefaultMutableTreeMain extends JPanel {
         protected DefaultMutableTreeNode    top = new DefaultMutableTreeNode("Options");
         protected DefaultMutableTreeNode      selectedNode = null;
         protected final JTree tree;
         protected final JTextField jtf;
        protected Enumeration      vEnum = null;
         private      TreeModel                m;
         protected  DefaultMutableTreeNode      getDefaultMutableTreeNode()  {
              //textArea.getText();
                   return selectedNode;
         protected  DefaultMutableTreeNode setDefaultMutableTreeNode(DefaultMutableTreeNode tt)  {
              //textArea.getText();
                   selectedNode = tt;
                   return selectedNode;
         protected  TreeModel getJTModel()  {
              //textArea.getText();
                   return m;
         protected  TreeModel setJTModel(TreeModel ta)  {
                   m = ta;
                   return m;
           public DefaultMutableTreeMain() {
             setSize(300,300);
             setLayout(new BorderLayout());
             DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
             top.add(a);
             DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
             a.add(a1);
             DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
             a.add(a2);
             DefaultMutableTreeNode a3 = new DefaultMutableTreeNode("A3");
             a.add(a3);
             DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
             top.add(b);
             DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
             b.add(b1);
             DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
             b.add(b2);
             DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
             b.add(b3);
             DefaultMutableTreeNode c = new DefaultMutableTreeNode("C");
             a3.add(c);
             DefaultMutableTreeNode c1 = new DefaultMutableTreeNode("C1");
             c.add(c1);
             DefaultMutableTreeNode c2 = new DefaultMutableTreeNode("C2");
             c.add(c2);
             DefaultMutableTreeNode c3 = new DefaultMutableTreeNode("C3");
             c.add(c3);
             DefaultMutableTreeNode c4 = new DefaultMutableTreeNode("C4");
             c.add(c4);
             DefaultMutableTreeNode c5 = new DefaultMutableTreeNode("C5");
             c.add(c5);
             tree = new JTree(top);
             JScrollPane jsp = new JScrollPane(tree);
             jsp.setPreferredSize(new Dimension(400,300));
             add(jsp, BorderLayout.CENTER);
             jtf = new JTextField("", 20);
             add(jtf, BorderLayout.SOUTH);
               tree.addMouseListener(new MouseAdapter() {
               public void mouseClicked(MouseEvent me) {
                  TreePath   path = tree.getSelectionPath();
                  DefaultMutableTreeNode      selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
                 TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
                 setDefaultMutableTreeNode(selectedNode);
                     System.out.println("Current node selected is (tp.toString()=" + tp.toString());
                     System.out.println("Current node selected is getDefaultMutableTreeNode()=" + getDefaultMutableTreeNode());
                 if (tp != null){
                     jtf.setText(tp.toString());
                      System.out.println("It Has Children as selectedNode.getChildCount()= " + selectedNode.getChildCount());
                            Enumeration vEnum = selectedNode.children();
                                int i = 0;
                                while(vEnum.hasMoreElements()){
                                    System.out.println("2 selectedNode = " +  path.toString() + "  has " + i++ + " Children in vEnum.nextElement(" + i + ") = " + vEnum.nextElement());
                 else
                   jtf.setText("");
           public static void main(String[] args) {
             JFrame frame = new JFrame();
             frame.getContentPane().add(new DefaultMutableTreeMain());
             frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
             frame.setSize(400, 400);
             frame.setVisible(true);
         }[2]. PB Panel code
    package com.atest;
    import java.awt.BorderLayout;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.JPanel;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.*;
    import javax.swing.JButton;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    public class DefaultMutableTreeSub extends JPanel implements java.io.Serializable{
      private JButton removeButton;
      private JButton addButton;
      JTree tree;
      private TreeModel      m;
      protected TreeDragSource ds;
      protected TreeDropTarget dt;
    protected  TreeModel getJTModel()  {
              //textArea.getText();
                   return m;
    protected  TreeModel setJTModel(TreeModel ta)  {
                   m = ta;
                   return m;
    protected DefaultTreeModel model;
    protected DefaultMutableTreeNode rootNode;
    DefaultMutableTreeMain dmm = null;
    JPanel inputPanel  = new JPanel();
      public JPanel SLTreeDNDEditableDynamic(DefaultMutableTreeMain tdnd ) {
        //super("Rearrangeable Tree");
        setSize(400,450);
        dmm = tdnd;
             setLayout(new BorderLayout());
             inputPanel.setLayout(new BorderLayout());
             JPanel outputPanel = new JPanel();
             System.out.println("Sub selectedNode tdnd= " + tdnd);
             tdnd.tree.addTreeSelectionListener(new TreeSelectionListener(){
                  public void valueChanged(TreeSelectionEvent evt){
                  TreePath[] paths = evt.getPaths();
                  TreePath   path = dmm.tree.getSelectionPath();
                  DefaultMutableTreeNode      selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
                 DefaultMutableTreeNode itemNode = dmm.getDefaultMutableTreeNode();
                     System.out.println("Sub node selected is dmm.getDefaultMutableTreeNode()=" + dmm.getDefaultMutableTreeNode());
                  model = new DefaultTreeModel(itemNode);
                  tree = new JTree(model);
                  System.out.println("Sub selectedNode paths= " + paths);
                  System.out.println("Sub selectedNode path= " + path);
                  System.out.println("Sub selectedNode = " + selectedNode);
                  System.out.println("Sub itemNode = " + itemNode);
                  tree.putClientProperty("JTree.lineStyle", "Angled");
                  tree.setRootVisible(true);
                   inputPanel.add(new JScrollPane(tree),BorderLayout.CENTER);
             return inputPanel;
         public DefaultMutableTreeSub() {
              super();
    }thanks
    sunny

    Thanks so much, I use your code and import followig:
    import java.util.ArrayList;
    import java.awt.List;
    but
    private static List<Object> getChildNodes(JTree j) {
         Object parent = j.getLastSelectedPathComponent();
         int childNodeCount = j.getModel().getChildCount(parent);
         List<Object> results = new ArrayList()<Object>;
         for (i = 0; i < childNodeCount; i++) {
              results.add(parent, i);
         return results;
    here List<Object> and ArrayList()<Object> show red,
    Is my JDK version problem??
    my one is JKD
    C:\temp\swing>java -version
    java version "1.4.2_08"
    Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_08-b03)
    Java HotSpot(TM) Client VM (build 1.4.2_08-b03, mixed mode)
    Error as follows:
    C:\temp\swing>javac DefaultMutableTreeSub.java
    DefaultMutableTreeSub.java:38: <identifier> expected
    private static List<Object> getChildNodes(JTree j) {
    ^
    1 error
    any idea??
    Thanks

  • How to get the path when i select a directory or a file in a JTree

    How to get the path when i select a directory or a file in a JTree

    import java.lang.*;
    import java.io.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.HeadlessException;
    import javax.swing.event.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.util.Iterator;
    * @author Frederic FOURGEOT
    * @version 1.0
    public class JTreeFolder extends JPanel {
    protected DefaultMutableTreeNode racine;
    JTree tree;
    protected JScrollPane scrollpane;
    final static int MAX_LEVEL = 1; // niveau max de descente "direct" dans l'arborescence
    * Sous-classe FSNode
    * @author Frederic FOURGEOT
    * @version 1.0
    private class FSNode extends DefaultMutableTreeNode {
    File file; // contient le fichier li� au noeud
    * Constructeur non visible
    private FSNode() {
    super();
    * Constructeur par initialisation
    * @param userObject Object
    FSNode(Object userObject) {
    super(userObject);
    * Constructeur par initialisation
    * @param userObject Object
    * @param newFile File
    FSNode(Object userObject, File newFile) {
    super(userObject);
    file = newFile;
    * Definit le fichier lie au noeud
    * @param newFile File
    public void setFile(File newFile) {
    file = newFile;
    * Renvoi le fichier lie au noeud
    * @return File
    public File getFile() {
    return file;
    public JTree getJTree(){
         return tree ;
    * Constructeur
    * @throws HeadlessException
    public JTreeFolder() throws HeadlessException {
    File[] drive;
    tree = new JTree();
    // cr�ation du noeud sup�rieur
    racine = new DefaultMutableTreeNode("Poste de travail");
    // cr�ation d'un noeud pour chaque lecteur
    drive = File.listRoots();
    for (int i = 0 ; i < drive.length ; i++) {
    FSNode node = new FSNode(drive, drive[i]);
    addFolder(drive[i], node); // on descend dans l'arborescence du lecteur jusqu'� MAX_LEVEL
    racine.add(node);
    // Gestion d'evenement sur JTree (on �coute les evenements TreeExpansion)
    tree.addTreeExpansionListener(new TreeExpansionListener() {
    public void treeExpanded(TreeExpansionEvent e) {
    // lorsqu'un noeud est ouvert
    // on descend dans l'arborescence du noeud jusqu'� MAX_LEVEL
    TreePath path = e.getPath();
    FSNode node = (FSNode)path.getLastPathComponent();
    addFolder(node);
    ((DefaultTreeModel)tree.getModel()).reload(node); // on recharche uniquement le noeud
    public void treeCollapsed(TreeExpansionEvent e) {
    // lorsqu'un noeud est referm�
    //RIEN
    // alimentation du JTree
    DefaultTreeModel model = new DefaultTreeModel(racine);
    tree.setModel(model);
         setLayout(null);
    // ajout du JTree au formulaire
    tree.setBounds(0, 0, 240, 290);
    scrollpane = new JScrollPane(tree);
         add(scrollpane);
         scrollpane.setBounds(0, 0, 240, 290);
    * Recuperation des sous-elements d'un repertoire
    * @param driveOrDir
    * @param node
    public void addFolder(File driveOrDir, DefaultMutableTreeNode node) {
    setCursor(new Cursor(3)); // WAIT_CURSOR est DEPRECATED
    addFolder(driveOrDir, node, 0);
    setCursor(new Cursor(0)); // DEFAULT_CURSOR est DEPRECATED
    * Recuperation des sous-elements d'un repertoire
    * (avec niveau pour r�cursivit� et arr�t sur MAX_LEVEL)
    * @param driveOrDir File
    * @param node DefaultMutableTreeNode
    * @param level int
    private void addFolder(File driveOrDir, DefaultMutableTreeNode node, int level) {
    File[] fileList;
    fileList = driveOrDir.listFiles();
    if (fileList != null) {
    sortFiles(fileList); // on tri les elements
    // on ne cherche pas plus loin que le niveau maximal d�finit
    if (level > MAX_LEVEL - 1) {return;}
    // pour chaque �l�ment
    try {
    for (int i = 0; i < fileList.length; i++) {
    // en fonction du type d'�l�ment
    if (fileList[i].isDirectory()) {
    // si c'est un r�pertoire on cr�� un nouveau noeud
    FSNode dir = new FSNode(fileList[i].getName(), fileList[i]);
    node.add(dir);
    // on recherche les �l�ments (r�cursivit�)
    addFolder(fileList[i], dir, ++level);
    if (fileList[i].isFile()) {
    // si c'est un fichier on ajoute l'�l�ment au noeud
    node.add(new FSNode(fileList[i].getName(), fileList[i]));
    catch (NullPointerException e) {
    // rien
    * Recuperation des sous-elements d'un noeud
    * @param node
    public void addFolder(FSNode node) {
    setCursor(new Cursor(3)); // WAIT_CURSOR est DEPRECATED
    for (int i = 0 ; i < node.getChildCount() ; i++) {
    addFolder(((FSNode)node.getChildAt(i)).getFile(), (FSNode)node.getChildAt(i));
    setCursor(new Cursor(0)); // DEFAULT_CURSOR est DEPRECATED
    * Tri une liste de fichier
    * @param listFile
    public void sortFiles(File[] listFile) {
    triRapide(listFile, 0, listFile.length - 1);
    * QuickSort : Partition
    * @param listFile
    * @param deb
    * @param fin
    * @return
    private int partition(File[] listFile, int deb, int fin) {
    int compt = deb;
    File pivot = listFile[deb];
    int i = deb - 1;
    int j = fin + 1;
    while (true) {
    do {
    j--;
    } while (listFile[j].getName().compareToIgnoreCase(pivot.getName()) > 0);
    do {
    i++;
    } while (listFile[i].getName().compareToIgnoreCase(pivot.getName()) < 0);
    if (i < j) {
    echanger(listFile, i, j);
    } else {
    return j;
    * Tri rapide : quick sort
    * @param listFile
    * @param deb
    * @param fin
    private void triRapide(File[] listFile, int deb, int fin) {
    if (deb < fin) {
    int positionPivot = partition(listFile, deb, fin);
    triRapide(listFile, deb, positionPivot);
    triRapide(listFile, positionPivot + 1, fin);
    * QuickSort : echanger
    * @param listFile
    * @param posa
    * @param posb
    private void echanger(File[] listFile, int posa, int posb) {
    File tmpFile = listFile[posa];
    listFile[posa] = listFile[posb];
    listFile[posb] = tmpFile;

  • Having multiple nodes with the same name in JTree!!!???

    Hi!
    I want to be able to have folders or files with the same name in different locations in my JTree. But if I do so the last one always overwrites the previous one.
    I have a vector with strings like root\aaa\bbb\ccc\ddd.doc, root\aaa\bbb\eee.doc, root\aaa\ccc\fff.doc etc. In this case ccc\ddd.doc out of the first string would disapear.
    In this post you can see how I add the nodes:
    http://forum.java.sun.com/thread.jsp?forum=31&thread=54920
    Is this because it adds everything in the same level or what? A solution/workaround would be much appreciated.
    Tobias

    Use this example...
    public class TreeDemo {
    private JFrame frame;
    private JTree tree;
    public TreeDemo (JTree tr) throws Exception {
    frame=new JFrame();
    frame.getContentPane().setLayout(new BorderLayout());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    edit=new JEditorPane();
    frame.getContentPane().add frame.getContentPane().add(tr,BorderLayout.CENTER);
    frame.getContentPane().add(new JButton("ok"),BorderLayout.SOUTH);
    frame.pack();
    frame.show();
    public static void main(String[] argv)
    throws Exception
    Vector v=new Vector();
    v.add(0,"c:\\first\\abc");
    v.add(1,"c:\\first\\abc\\word1.doc");
    v.add(2,"c:\\first\\abc\\description.doc");
    v.add(3,"c:\\first\\def ");
    v.add(4,"c:\\first\\der\\tor1.doc");
    TreeDemo html = new TreeDemo (createTree(v));
    private static JTree createTree(Vector v) {
    JTree tree = null;
    DefaultMutableTreeNode root = null;
    Iterator i = v.iterator();
    String subStr;
    DefaultMutableTreeNode parent=null;
    root = new DefaultMutableTreeNode("ROOT");
    tree = new JTree(root);
    parent=root;
    while (i.hasNext()) {
    String path = (String)i.next();
    StringTokenizer st = new StringTokenizer(path,"\\");
    while (st.hasMoreTokens()) {
    subStr = st.nextToken();
    DefaultMutableTreeNode current=findObject(parent,subStr);
    if (current==null) {
    DefaultMutableTreeNode node = new DefaultMutableTreeNode(subStr);
    parent.add(node);
    parent=node;
    else {
    parent=current;
    parent=root;
    return tree;
    private static DefaultMutableTreeNode findObject(DefaultMutableTreeNode parent,String value) {
    for (int i=0; i<parent.getChildCount(); i++) {
    DefaultMutableTreeNode node=(DefaultMutableTreeNode)parent.getChildAt(i);
    if (node.getUserObject().equals(value)) {
    return node;
    return null;
    best regards
    Stas

  • Save and load jtree

    Hi,
    I have a jtree which I would like to save and then load and display in a JPanel. Just for info, the nodes of the tree are instances of a user object i have created. Now I have looked into two ways of doing this:
    1) Serialize the actual JTree object; write it to a file using objectoutputstream and then read it in using objectinputstream, OR
    2) Serialize the tree model again using objectoutputstream then read the model back and create a new JTree initialising with the model i read in.
    I made some progress using the second approach, but when I load the tree model back and create a new tree with that model it just displays as a blank root with blank children. (Although the tree structure is the same).
    What am i doing wrong?
    The code is:
    public void saveTheTree() {
            TreeModel tm = tree1.getModel();
            try {
                 ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("treeModel"));
                 out.writeObject(tm);//the actual tree object
                 out.flush();
                 out.close();
            catch(IOException e){}
      public void openTheTree() {
           ObjectInputStream in = null;
             try {
                 in = new ObjectInputStream(new FileInputStream("treeModel"));
                 TreeModel atm = (TreeModel) in.readObject();
                 JTree loaded = new JTree(atm);
                 abPanel3.removeAll();
                 abPanel3.revalidate();
                 abPanel3.add(loaded, BorderLayout.CENTER);
                 abPanel3.revalidate();
             catch(Exception e) {
                  e.printStackTrace();
      }abPanel3 is where the tree is displayed and tree1 is my tree.
    Any help would be much appreciated!

    well the leaves are defaultmutabletreenodes instantiated with a user object which attaches a link and level to each one. According to the java documentation, defaultmutabletreenode is serializable, but do i need to serialize each node of the tree as well?
    Has anyone managed to save and load a jtree before?
    Thanks.

  • Help with JTree refresh

    I am having trouble displaying a JTree with newly added nodes.
    I have a JTree, inside a JPanel, JScrollPane and JSplitPane.
    I create the JTree with a single root node which displays correctly.
    I update the JTree with new children which displays correctly.
    Using the same exact routine as above - I add additional new children to the root, the new children do not display in the JTree.
    I have confirmed that I am using the correct tree and root node in debug that the tree/node objects has been correctly updated. It is just not displaying the new children to the root.
    I can expand and collapse the tree which does not show the new children, just the original populated root.
    After the root has been updated, I have tried a number of methods to resolve: tree/jpanel/jscrollpane/jsplitpane .revalidate, invalidate, repaint, etc.
    I am using v1.4.1.
    What am I missing here?
    Thanks in advance.

    i use two classes fro add or insert nodes in a tree, one adds the node at the same level of the current selected node, and the other intert it inside:
    // InsertaTreeConfAction.java
    package ayto;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.tree.*;
    public class InsertaTreeConfAction extends AbstractAction {
    TreeConf treeConf;
    MenuTreeConf menuPrincipal;
    TreeConfAppAyto confNodo;
    DefaultTreeModel model;
    TreeTreeConf tree;
    public InsertaTreeConfAction(TreeConf treeConf,String text) {
    super(text);
    this.treeConf = treeConf;
         InitAction();
    public InsertaTreeConfAction(TreeConf treeConf, String text, Icon icon) {
    super(text, icon);
    this.treeConf = treeConf;
         InitAction();
    public void InitAction(){
         menuPrincipal = treeConf.getMenu();
         confNodo = treeConf.selNodo;
         model = treeConf.getTree().getMyModel();
         tree = treeConf.getTree();
    public void actionPerformed(ActionEvent ev) {
              model = treeConf.getTree().getMyModel();
              TreePath tp = tree.getSelectionPath( );
         MutableTreeNode insertNode = (MutableTreeNode)tp.getLastPathComponent( );
         int insertIndex = 0;
              if (insertNode.getParent( ) != null) {
              MutableTreeNode parent = (MutableTreeNode)insertNode.getParent( );
              //insertIndex = parent.getIndex(insertNode) + 1;
              //insertNode = parent;
         MutableTreeNode node = new DefaultMutableTreeNode(new TreeConfAppAyto("Nodo Insertado"));
         model.insertNodeInto(node, insertNode, insertIndex);
    treeConf.estadoConfApp = TreeConf.NODO_MODIFICADO;
    treeConf.updater.update(); // esto no colapsa el arbol
    treeConf.setTitle("AYTO de Huelva - Configuraci�n de men�s: "+treeConf.fileAct);
    // AnadeTreeConfAction.java
    package ayto;
    import javax.swing.*;
    import java.awt.event.*;
    import java.awt.*;
    import java.io.*;
    import javax.swing.tree.*;
    public class AnadeTreeConfAction extends AbstractAction {
    TreeConf treeConf;
    MenuTreeConf menuPrincipal;
    TreeConfAppAyto confNodo;
    DefaultTreeModel model;
    TreeTreeConf tree;
    public AnadeTreeConfAction(TreeConf treeConf,String text) {
    super(text);
    this.treeConf = treeConf;
         InitAction();
    public AnadeTreeConfAction(TreeConf treeConf, String text, Icon icon) {
    super(text, icon);
    this.treeConf = treeConf;
         InitAction();
    public void InitAction(){
         menuPrincipal = treeConf.getMenu();
         confNodo = treeConf.selNodo;
         model = treeConf.getTree().getMyModel();
         tree = treeConf.getTree();
    public void actionPerformed(ActionEvent ev) {
              model = treeConf.getTree().getMyModel();
              TreePath tp = tree.getSelectionPath( );
         MutableTreeNode insertNode = (MutableTreeNode)tp.getLastPathComponent( );
         int insertIndex = 0;
              if (insertNode.getParent( ) != null) {
              MutableTreeNode parent = (MutableTreeNode)insertNode.getParent( );
              insertIndex = parent.getIndex(insertNode) + 1;
              insertNode = parent;
         MutableTreeNode node = new DefaultMutableTreeNode(new TreeConfAppAyto("Nodo A�adido"));
         model.insertNodeInto(node, insertNode, insertIndex);
    treeConf.estadoConfApp = TreeConf.NODO_MODIFICADO;
    treeConf.updater.update(); // esto no colapsa el arbol
    treeConf.setTitle("AYTO de Huelva - Configuraci�n de men�s: "+treeConf.fileAct);

  • Database and JTree

    I have table in access entitled employees and wish to generate a JTree to show the organizational heirarchy of the company. I feel like I've followed the steps properly but the Jtrees either don't work or they work with the wrong data.
    "Perform a query to obtain the name of the employee. If you are at the root node (level 0), just change the value of the current node to the name you got from the query, otherwise, create a child node and set its value to be that name. Perform another query to get the employee IDs of all the employees whose manager is the current employee. Loop through this result set, recursively calling the method for each of the employees in the resultset from step (4)."[]
        public static void generateTree(DefaultMutableTreeNode node, int id, int level){
            DbSource dbs = new DbSource("EmpDb");
            if (dbs.isConnected()){
             boolean success = dbs.processQuery("select firstname, lastname from employees", false);
             if(success){
                 while(dbs.nextRecord()){
                  DefaultMutableTreeNode newNode;
                    if (level==0){
                        node.setUserObject(dbs.getField(1)+ " " + dbs.getField(2));
                        newNode=node;
                    else{
                        newNode = new DefaultMutableTreeNode(dbs.getField(1) + " " + dbs.getField(2));
                        node.add(newNode);               
                 boolean success2 = dbs.processQuery("select employeeid from employees where " + id+ " = manager", false);
                 if (success2){
                 while (dbs.nextRecord()){
                      generateTree(newNode, id, level+1);                      
        }Any quick hints are appreciated.

    Well, you didn't say what was wrong with the result of this. But that doesn't matter because I can see a lot of things wrong with the code.
    First you don't have anything that gets the level-zero node. (The president of the company or whatever that is.) You should do this outside the recursively-called method and create a node that contains that person's name. Then call the method, passing it that node.
    Second, in your posted code you have something that reads the entire file at every level. What's that for?
    Third, the last four lines of that method look like the actual code you need: get the employees who report to the manager in the current node. However you need something that creates a new node for each of those employees and adds it to the manager node.
    Fourth, you don't seem to use that "level" parameter anywhere. I don't think you have any need for it.
    Fifth, and I don't know if this is a problem, you will need to be able to process several DbSource objects simultaneously. Possibly you can, but it's possible to code that sort of thing so that you can't.

  • JTree not showing plus/minus signs

    Hi,
    I'm having a strange problem with JTree when implementing my own DefaultTreeCellRenderer: the renderer is shown correctly, but the plus and minus signs are gone!
    My getTreeCellRendererComponent implementation actually creates a new JPanel and returns it instead of the default one. Can that be the problem? How can I make these plus/minus signs come back?
    Thanks, U

    I have seen something a little different on my CustomCellRenderer where the plus minus sign is replaced with some default arrow icon and where it comes from I have no clue. I basically have a 3 level deep tree and its at the B level where this icon appears.
    http://www.matthewscorp.com/images/JTreeError.jpg
    For the life of me I can't figure this one out. I have tried all ideas like set all the renderer icons or the LAF properties icons and still this blue arrow appears. Any ideas would help on both mine and the original poster.

  • JTree genius needed

    I need some serious help with the JTree as I am very confused as to why my tree is behaving in a certain manner. Basically I have saw AbstractTreeModel.java ina thread on thsi forum which emplements TreeModel. My tree is populated by data coming into the application over a network stream.
    Basically whats going on is, I am able to insert nodes and in fact change the valeu of nodes while the
    parent node above the node i am inserting is collapsed.Once the node is expanded I can change the value(in this case teh color of the icon) of the node, but the new nodes being inserted in the tree do not show up.
    Very confusing! I mean I see the same behavior when the parent is expanded or collapsed. But The nodes do not apear when the parent is expanded. In fact, after expanding and collapsing they no longer appear at all. What happens to my applciation when the node is expanded???
    Any thoughts

    Thanks for replying. I tried to do what you said. I think it would be best if i sent you some code.
    Here is my model which extends yours.
    public class ResourceTreeModel extends AbstractTreeModel {
    Vector listeners;
    public ResourceTreeModel(ResourceTypeNode r) {
    if(r == null) {
    throw new IllegalArgumentException("Root is null.");
    setRoot(r);
    /*This method adds
    *the new ResourceNode to
    *the tree model with
    *the specified ResourceTypeNode
    *as the parent.
    public void nodeInserted(ResourceTypeNode parent, Object node, int index) {
    //Resource type nodes
    //are where we insert
    //ResourceNodes
    if(node instanceof ResourceTypeNode) {
    parent.setChild(index, node);
    else if(node instanceof ResourceNode) {  
    parent.setChild(index, node);
    else {
    index = getIndexOfChild((Object)parent, node);
    TreePath tp = new TreePath(getPathToRoot(node));
    int[] ai = { index };
    Object[] ac = {node};
    fireTreeNodesInserted(new TreeModelEvent(this, tp, ai, ac));
    public void nodeChanged(Object node) {
    TreePath tp = new TreePath(getPathToRoot(node));
    fireTreeNodesChanged(new TreeModelEvent(this, tp, null, null));
    public Object getChild(Object parent, int index) {
    if(parent instanceof ResourceTypeNode) {
    return ((ResourceTypeNode)parent).getChildAt(index);
    return null;
    * Returns the number of children of parent.
    * @param parent the parent node
    * @return the child count
    public int getChildCount(Object parent) {
    if(parent instanceof ResourceTypeNode) {
    return ((ResourceTypeNode)parent).getChildCount();
    return 0;
    * Returns the index of child in parent.
    * @param parent the parent node
    * @param child the child node
    * @return the index of the child node in the parent
    public int getIndexOfChild(Object parent, Object child) {
    if(parent instanceof ResourceTypeNode && child instanceof ResourceTypeNode ) {
    return ((ResourceTypeNode)parent).getIndex((ResourceTypeNode)child);
    else if(parent instanceof ResourceTypeNode && child instanceof ResourceNode ) {
    return ((ResourceTypeNode)parent).getIndex((ResourceNode)child);
    else {
    return -1;
    public Object getParent(Object obj) {
    Object parent = null;
    if(obj instanceof ResourceTypeNode) {
    parent = ((ResourceTypeNode)obj).getParent();
    else if(obj instanceof ResourceNode) {
    parent = ((ResourceNode)obj).getParent();
    else {
    return parent;
    public boolean isLeaf(Object node) {
    return (node instanceof ResourceNode);
    Here is the class in which i build my tree at the start of application
    /*Create the apprpriate
    *ResourceTypeNodes for
    *the tree. The keys from
    *the C2App.resourceTypes
    *TreeMap are used to create
    *the JTree nodes.
    *A StringTokenizer is used
    *to dissect the segments
    *of the resource names
    *to build category nodes.
    public void init() {
    root = new ResourceTypeNode("Resources");
    treeModel = new ResourceTreeModel(root);
    //Need set of names
    //for resources.
    Set rTypesKeySet = C2App.resourceTypes.keySet();
    Iterator iter = rTypesKeySet.iterator();
    ResourceTypeNode key = null;
    ResourceTypeNode category = null;
    //Iterate through
    //all types.
    while(iter.hasNext()) {
    //Full Resource
    //Type Name.
    String currentCategory = iter.next().toString();
    //Need to determine the
    //level from root this
    //node should go into.
    StringTokenizer stok = new StringTokenizer(currentCategory, "::");
    //Levels from
    //root to node
    //to create.
    int levelFromRoot = stok.countTokens();
    //Node goes under
    //root parent node.
    if(currentCategory.lastIndexOf("::") == -1) {
    resourceTypeNodes.put(currentCategory, new ResourceTypeNode(currentCategory));
    ResourceTypeNode parent = root;
    parent.add((ResourceTypeNode)resourceTypeNodes.get(currentCategory));
    treeModel.nodeInserted(parent, resourceTypeNodes.get(currentCategory), parent.getChildCount());
    //Node goes under
    //a parent node other
    //than root.
    else {
    resourceTypeNodes.put(currentCategory, new ResourceTypeNode(currentCategory));
    String parentName = Resource.parentOf(currentCategory);
    ResourceTypeNode parent = (ResourceTypeNode)resourceTypeNodes.get(parentName);
    parent.add((ResourceTypeNode)resourceTypeNodes.get(currentCategory));
    treeModel.nodeInserted(parent, resourceTypeNodes.get(currentCategory), parent.getChildCount());
    This works fine I am able to open app and see all the resourcetype nodes wich are not leaves
    the problem i am having is with the code snippet below.
    //Existing resource?
    if(existingResource) {
    //Change value
    //of node
    ((ResourceTreeModel)C2App.theGUI.resourceTreePanel.resourceTree.getModel()).nodeChanged(C2App.theGUI.resourceTreePanel.resourceNodes.get(resourceID));
    //Is this node
    //displayed in
    //the ResourceInfoPanel?
    if(ResourceInfoPanel.getResourceDisplayedID().equals(resourceID)) {
    //Update panel.
    c2app.gui.ResourceInfoPanel.updatePanel(r);
    //New resource
    //for tree?
    else {
    //Get type so
    //that we can
    //decide which
    //parent node
    //the node should
    //be placed under.
    String type = r.type;
    //Get Parent node.
    ResourceTypeNode parent = (ResourceTypeNode)C2App.theGUI.resourceTreePanel.resourceTypeNodes.get(type);
    //Insert node
    //into tree under
    //parent.
    parent.add((ResourceNode)C2App.theGUI.resourceTreePanel.resourceNodes.get(resourceID));
    ((ResourceTreeModel)C2App.theGUI.resourceTreePanel.resourceTree.getModel()).nodeInserted(parent, C2App.theGUI.resourceTreePanel.resourceNodes.get(resourceID), parent.getChildCount());
    //Expand path
    //to this node
    /*Object[] tn = ((ResourceTreeModel)(C2App.theGUI.resourceTreePanel.resourceTree.getModel())).getPathToRoot(parent);
    System.out.println();
    for(int j = 0; j < tn.length; j++) {
    System.out.println("TN: " + tn[j].toString());
    System.out.println();
    TreePath tp = new TreePath(tn);
    System.out.println();
    System.out.println("TP: " + tp.toString());
    System.out.println();
    C2App.theGUI.resourceTreePanel.resourceTree.expandPath(tp);*/
    //((ResourceTreeModel)(C2App.theGUI.resourceTreePanel.resourceTree.getModel())).reload();
    //C2App.theGUI.resourceTreePanel.expandTree();
    C2App.theGUI.resourceTreePanel.resourceTree.treeDidChange();
    //Update the map.
    break;
    basically if the node row is collapsed which i am adding to the add occurs.
    but if it is expanded i do not see the new node.
    Funny that the update of the node occurs if existing resource is true.
    So that makes me wonder why nodeChanged works but not nodeInserted
    i analyzed all the way down to fireTreeNodesInserted with println and it is being called it tells me nod eis being added
    d not understand why when node is expanded cant add child to it.
    Thanks again I hope you can help me
    Vinny

  • JTree node parsing

    Hi
    I have a JTree where the which has a list of subnodes( please note that i m adding new functionality to existing java application )
    the new functionality must on user click on a node , must do list all files under that node and process those files
    i have parsed the node as follows , is this a elegant way ? is there any other better way to do it
    levels of parsing is fixed to 4 levels ( so 4 time for loops )
    public void valueChanged(TreeSelectionEvent e) {
    NavigatorTreeNode node= null;
    if (obj instanceof NavigatorTreeNode) {
         node = (NavigatorTreeNode)obj;
    if (node == null) return;
    String path = node.getFileName();
    boolean isLeaf, isRoot;
    isLeaf = node.isLeaf();
    isRoot = node.isRoot();     
    if(!isLeaf){
         for(int i = 0 ; i < node.getChildCount(); i++){
         System.out.println(node.getChildAt(i));
                  for(int j = 0 ; j < node.getChildAt(i).getChildCount(); j++){
                  System.out.println("     "+node.getChildAt(i).getChildAt(j));
              for(int k = 0 ; k < node.getChildAt(i).getChildAt(j).getChildCount(); k++){
              System.out.println("              "+node.getChildAt(i).getChildAt(j).getChildAt(k));
                   for(int l = 0 ; l < node.getChildAt(i).getChildAt(j).getChildAt(k).getChildCount(); l++){
                   System.out.println("                   "+node.getChildAt(i).getChildAt(j).getChildAt(k).getChildAt(l));
    //.......... furthur code ............
    } // End of valueChanged     

    Depending on how you define 'elegance', you might want to have a look at recursion?
    * I have not tested this code, so there's most likely a little flaw here and there.
    * However, it might give you an idea as to how you can make your code a little
    * more elegant?
    public void valueChanged(TreeSelectionEvent e) {
      if (e.getPath().getLastPathComponent() instanceof NavigatorTreeNode) {
        printNode((NavigatorTreeNode) e.getPath().getLastPathComponent(), 0);
    private void printNode(NavigatorTreeNode n, int l) {
      if (n == null) {
        return;
      String inset = "-";
      for (int i = 0; i < l; i++) {
        inset += "-";
      System.out.println(inset + " " + n.toString());
      for (int i = 0; i < n.getChildCount(); i++) {
        printNode(n.getChild(i), l + 1);
    }

  • JTree Node Color, to distinguish between different activities

    Hi,
    Situation:          Dynamic JTree (Tree is constructed from as a result of Database). User has the option to either Enable / Disable node and can repeat the activities but restricted only one activity per node, the node is to be highlighted; to restrict the user from further activities.
    Problem:          Am a newbie to swing, after searching the forum for the same, i found few good solutions which are specific to color change of specific selected node, in a temporary context.
         But we need the node color change within a same level; to distinguish either the node is either enabled / disabled.
    Your help is appreciated,

    durino13 wrote:
    1. Is the approach above a good approach, how to load children 'lazilly'?Sounds pretty reasonable to me.
    2. I also use custom renderer to display different icons for every "tree" level. When I initially expand the 4th level, everything works fine !!! Then I collapse the 4th level and expand it again and here my problem starts: my 4th level icon is set to 'root level icon' instead of '4th level' icon. This does not happen, if computerNode.removeAllChildren(); method is removed from listening above
    Any idea, what am i doing wrong?Ummmm... Load the model the first time (only) the node is expanded... Putz!
    And I suggest you listen deeply to Mr Jacobs... He really does know what he's talking about ;-)
    ... and not this time, but in future: Swing questions are best asked in [THE Swing Forum|http://forums.sun.com/forum.jspa?forumID=57].
    Cheers. Keith.

Maybe you are looking for

  • Lost mail in lion and air book

    My 4 month old Mac Air started to freeze intermittently.  Having been told at Tech Support "oh they do that", I went to the Genius Bar, passed all the hardware tests, and agreed to a wipe and restore of lion, secure in the knowledge I had backed ever

  • JDeveloper 10g, ADF Faces & BC: List Binding Editor Bug?

    This problem comes up quite frequently, we have a form based on an entity based vo, one of the attributes is based on a read only list vo. When using the List Binding Editor to generate the jsp/pageDef code, the attributes do not show up in the "matc

  • Loading External JAR librarys in an applet

    HI all, I have an application that I would like to add an excell extention to. The extension is in the form of a JAR file, and I only want my applet to load this jar file when a menu item has ben clicked. I do not want the jar file to be loaded toget

  • How to know latest version of workbook

    hi, i have 3 workbooks with same name. but how to know which is latest? donn tell me see creation date. any other option other than that? neeraja

  • Java exception on "cache document" post to CRM from UCCX

    We recently implemented a CRM which supports a method of 'call pop', where information is POST'ed from our UCCX application to an inbound point. It works perfectly. The problem we're seeing is that if that inbound point is unavailable, our applicatio