Propagate JTree.

I am very new to JAVA. I am building a GUI where I need each of a set of menu buttons to build a tree. I am having problems with the event handling part of JAVA because I need to build not a static tree but on that's built as a result of clicking the corresponding menu buttons. For example, when a user clicks on 'New' in the 'Build' menu it creates a root or 'Child' int the "Build" it creates a child.

Have you looked at the tutorial? There's a section on adding nodes to a tree dynamically.
http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html

Similar Messages

  • JTree, branch expanding and TreeWillExpandEvent

    You can expand a branch in JTree component either by double clicking the node's name or by single clicking the branch expanding icon (next to node icon). How can I determine which way was used when receiving the TreeWillExpandEvent ? It seem that it does not provide this information

    It looks to me like TreeWillExpandEvent does not retain the mouse click information from the underlying event that caused the expansion. Looks like you would need to provide a custom UI and event mechanism to propagate that information.
    Mitch Goldstein

  • Multi-parent JTree

    Hi! I would like to build a JTree with more than one parent is this possible? How to do it?

    Jenny,
    it is possible, but a pain in the neck. the multiple children are no problem, that's part of the tree classes.
    however, if a node has to have more than 1 parent you need to create a clone of that node and then you can add it to another parent. to keep the children you need to do a 'deep clone', ie clone the children as well.
    the problems start, if you want to allow editing of nodes, eg add/remove children. then you need to make sure you propagate the changes to all clones (this applies [possibly] to explode/collapse and selection as well).
    thomas

  • Pointer Confusion + global JTree

    Hi there,
    I wonder if it is possible to change the JTree represented in a JScrollPane if defined as follows:
    class A extends JPanel{
    static JTree m_tree;
    A(){
    JScrollPane treeView = new JScrollPane(m_tree);
    JSplitPane splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, treeView,someOtherView );
    this.setLayout(new BorderLayout());
    this.add("Center", splitPane );
    what I want to do is to show a completely different JTree (not just modifying certain elements, but exchanging it as a whole). Can this be done? I am rather sure, that it is possible, but I don't have an idea how, right at the moment. Should a method like:
    public static void set_and_Show_New_Tree(JTree tree){
    A.m_tree = tree;
    A.getContentPane().validate()
    be enough? I don't think so, because m_tree is not a pointer, but a complete Instance, so the contentpane does not know that there is a new JTree. But how to propagate this information and delete the old tree??
    I would really be grateful for any help :).
    Sincerely
    JebeDiAH

    Hi there,
    I wonder if it is possible to change the JTree represented in a JScrollPane if defined as follows:
    class A extends JPanel{
    static JTree m_tree;
    A(){
    JScrollPane treeView = new JScrollPane(m_tree);
    JSplitPane splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, treeView,someOtherView );
    this.setLayout(new BorderLayout());
    this.add("Center", splitPane );
    what I want to do is to show a completely different JTree (not just modifying certain elements, but exchanging it as a whole). Can this be done? I am rather sure, that it is possible, but I don't have an idea how, right at the moment. Should a method like:
    public static void set_and_Show_New_Tree(JTree tree){
    A.m_tree = tree;
    A.getContentPane().validate()
    be enough? I don't think so, because m_tree is not a pointer, but a complete Instance, so the contentpane does not know that there is a new JTree. But how to propagate this information and delete the old tree??
    I would really be grateful for any help :).
    Sincerely
    JebeDiAH

  • Exist a Jtree node.id or something like this ?

    I would want to retrieve a node using a unique 'id', for example the absolute index (into the total nodes count)
    Is there something like this ?
    Can I add a particular property to a node ? ( for example this 'id' if it does not exist )
    Another question :
    If I want to implement a search code, this 'id' can be useful, or must I transverse the whole Jtree
    Thanks

    Hello.
    Do the following:
    1. Go to the Apple Menu at the top left of the screen
    2. Select Software Update...
    3. Install any updates that are found.
    If the Amazon issue continues after these updates, then do this:
    1. Open Safari
    2. Erase any web address you have currently showing (for example www.apple.com or www.google.com)
    3. Type in www.amazon.com
    4. That should take you directly to amazon.com
    It should look like this in your Safari::

  • Problem with JTree and memory usage

    I have problem with the JTree when memory usage is over the phisical memory( I have 512MB).
    I use JTree to display very large data about structure organization of big company. It is working fine until memory usage is over the phisical memory - then some of nodes are not visible.
    I hope somebody has an idea about this problem.

    55%, it's still 1.6Gb....there shouldn't be a problem scanning something that it says will take up 300Mb, then actually only takes up 70Mb.
    And not wrong, it obviously isn't releasing the memory when other applications need it because it doesn't, I have to close PS before it will release it. Yes, it probably is supposed to release it, but it isn't.
    Thank you for your answer (even if it did appear to me to be a bit rude/shouty, perhaps something more polite than "Wrong!" next time) but I'm sitting at my computer, and I can see what is using how much memory and when, you can't.

  • Expanding a JTree Node on selection

    Hi,
    I have a need to expand the node on selection in a JTree. I would like all the children to be recursively expanded and selected.
    I believe the code lies somewhere with in JTree's TreeSelectionListener.
    The code I have is as follows
    tree.addTreeSelectionListener(new TreeSelectionListener()
    public void valueChanged(TreeSelectionEvent evt)
    TreePath[] paths = evt.getPaths();
    for (int i=0; i<paths.length; i++)
    if (evt.isAddedPath(i))
    DataNode node = (DataNode)paths.getLastPathComponent();
    ArrayList aList = node.children();
    if( !aList.isEmpty() )
    for(int j = 0; j<aList.size(); j++)
    TreePath tp = paths[i].pathByAddingChild(aList.get(j));
    System.out.println(tp);
    tree.expandPath(tp);
    }//for
    }//public void ValueChanged
    This does not seem to solve the problem..
    Your comments or help is very much appreciated..
    thanks
    S

    it does work for me (i do it in an action). what doesn't work for you?
    thomas
      public RecursiveExpander() {
        menu = new JPopupMenu();
        JMenuItem expand = new JMenuItem("Expand Recursive");
        expand.addActionListener(this);
        menu.add(expand);
      public void mousePressed(MouseEvent e) {
        theTree = (JTree)e.getSource();
        currentPath = theTree.getPathForLocation(e.getX(), e.getY());
        if ((currentPath != null) &&
            !((TreeNode)currentPath.getLastPathComponent()).isLeaf() &&
            (e.getModifiers() == InputEvent.BUTTON3_MASK)) {
          menu.show(theTree, e.getX(), e.getY());
      public void actionPerformed(ActionEvent ae) {
        new Thread(this).start();
      public void run() {
        theTree.setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
        try { expand(currentPath); }
        catch (OutOfMemoryError oom) {
          System.gc();
          System.err.println("RecursiveExpander: " + oom);
          JOptionPane.showMessageDialog(null, "RecursiveExpander: " + oom, "Error", JOptionPane.ERROR_MESSAGE);
        theTree.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
      private void expand(TreePath path) {
        theTree.expandPath(path);
        TreeNode start = (TreeNode)path.getLastPathComponent();
        for (int i = 0; i < start.getChildCount(); i++) {
          TreeNode node = start.getChildAt(i);
          if (!node.isLeaf()) {
            expand(path.pathByAddingChild(node));
    }

  • Rename a Jtree node directly & Popup Menu

    Pls assist with codes to rename a Jree node directly without using a dialog box or optionpane. I tried
    tree.startEditingAtPath(/* path of selected node*/);
    to go to edit mode and it does not work.
    II. Is it possible to attach different popmenu to the root, separate from the parent and child? Pls assist with code as the popupmenu i use at the moment shows up on the nodes(root, parent, leaf).
    I have benefiited greatly from questions asked and answers proferred at this forum and I use this opportunity to thank everyone greatly as I have migrated to Java based on all the materials sourced on the net.
    [email protected]

    public class AutomatedTreeMouseHandler extends MouseAdapter {
         public void mousePressed(MouseEvent e) {
              JTree tree = (JTree) (e.getSource());
              int x = e.getX();
              int y = e.getY();
              TreePath path = tree.getPathForLocation(x, y);
              if (path != null) {
                   // generate your popup here
    Dennis,
    are you saying that i have to define the popmenu for each category of node in the mouseadapter and att'd these to the tree depending on whether root, leaf or whatever type of node is selected?
    I will try this and revert.
    I can not make anything out of the reference giving with regard to renaming a node in edit mode.
    Pls provide more explanation and sample code, if necessary.
    Thanks a million.

  • How do I use JPanel as a leaf in JTree ?

    Hi All,
    I am a bit of a newbie and I've been trying to change the behavior of my application.
    I have a JTree that I now want to change the rendering of a leaf to be a JPanel. The JPanel will have a couple of JButtons and some text and the user can interact with the JButtons. I was successful in creating the JPanel, adding the buttons and then making my own TreeCellRenderer. Everything displays fine, but the user can not interact with the JButtons, whenever I click on a button in the leaf, the whole leaf is highlighted - I suppose I should not be surprised because this is probably behaving just a cell in a JTree should.
    So I searched the forums and used Google and have found several examples of people using JCheckBox as nodes/leaf(s) in a JTree but none with a JPanel as a leaf. I took one of the check box demos from here ( [http://www.coderanch.com/t/330630/Swing-AWT-SWT-JFace/java/add-swing-component-tree]) and then hacked it a bit but am stuck with the following error :
    Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to javax.swing.JPanel
    which is pointing to the line with JPanel temp2 = (JPanel) temp.getUserObject();
    Does anyone have either some code or suggestions to accomplish a leaf as a JPanel with some buttons ?
    Thanks in advance !
    import javax.swing.*;*
    *import javax.swing.tree.*;
    import java.awt.event.*;*
    *import java.awt.*;
    public class treedemo1 extends JFrame {
        public treedemo1() {
            super("TreeDemo");
            setSize(1500, 1500);
            JPanel p = new JPanel();
            p.setLayout(new BorderLayout());
            customLeafPanel cp1 = new customLeafPanel();
            customLeafPanel cp2 = new customLeafPanel();
            customLeafPanel cp3 = new customLeafPanel();
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("Query Results");
            DefaultMutableTreeNode n1 = new DefaultMutableTreeNode(cp1, false);
            DefaultMutableTreeNode n2 = new DefaultMutableTreeNode(cp2, false);
            DefaultMutableTreeNode n3 = new DefaultMutableTreeNode(cp3, false);
            root.add(n1);
            root.add(n2);
            root.add(n3);
            JTree tree = new JTree(root);
            p.add(tree, BorderLayout.NORTH);
            getContentPane().add(p);
            TestRenderer tr = new TestRenderer();
            tree.setEditable(false);
            tree.setCellRenderer(tr);
        public class customLeafPanel extends JPanel {
            public customLeafPanel() {
                JPanel clpPanel = new JPanel();
                JButton helloJButton = new JButton("Hello");
                this.add(helloJButton);
        public class TestRenderer implements TreeCellRenderer {
            transient protected Icon closedIcon;
            transient protected Icon openIcon;
            public TestRenderer() {
            public Component getTreeCellRendererComponent(JTree tree,
                    Object value,
                    boolean selected,
                    boolean expanded,
                    boolean leaf,
                    int row,
                    boolean hasFocus) {
                DefaultMutableTreeNode temp = (DefaultMutableTreeNode) value;
                JPanel temp2 = (JPanel) temp.getUserObject();
                return temp2;
            public void setClosedIcon(Icon newIcon) {
                closedIcon = newIcon;
            public void setOpenIcon(Icon newIcon) {
                openIcon = newIcon;
        public static void main(String args[]) {
            JFrame frame = new treedemo1();
            frame.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
            frame.pack();
            frame.setVisible(true);
    }

    Thank you TBM and DB for your replies ! Adding TBM's code does indeed fix the JPanel issue and as TBM indicated this does not actually solve my ultimate problem (Can I give you each 1/2 the Duke points?)
    As a newbie, I am still learning and DB pointed out that "You can however interact with an editor". So after reading the suggested tutorials and looking back at the example code that I hacked. I added the cellEditor back in and it WORKS ! Its funny, I deleted that bits of code from the example, assuming the cellEditor allows you to "edit" (ie change), not interact with it (symantics I guess)
    Thanks again guys for pointing this newbie in the right direction. Frankly I am somewhat surprised that I could finally begin to read and understand what the tutorial and suggestions are telling me ! What is one step up from a newbie ?
    unfortunately I can not post the code because the length of the message is > 5000 :(

  • Pages document doesn't propagate in iCloud

    Hello,
    I place a Pages document in iCloud (in the Pages application on my Mac, using 10.8.2), and it just won't propagate to my iPad (iOS 6).
    I have other documents there and it works so so (like iCloud usually does), but this one just won't move from my Mac.
    My internet connection is working flawlessly, iCloud is set-up everywhere, it's worked in the past.
    Why is this document stuck at "Waiting"?
    Loa

    Hello,
    From other apps, you mean? Did not check at the time. I'll make a new note on my Mac the next time I run into this problem to check.
    The Wi-Fi connectionwas working though, that I checked.
    Loa

  • Problem in Jtree while retrieving values from a hashtable

    Hi
    I am trying to show some values in a Jtree.I am receiving the values in a hashtable.The hashtable contains unique key but duplicate values.i want to show that values of that hashtable in a tree(but unique values)and under each value show all the key of it.can you please tell me how to do that.
    thanks

    If i understand right, you want to do something like this:
                   Hashtable values = yourhashtable;        
              DefaultMutableTreeNode root = new DefaultMutableTreeNode("Values");
              HashMap<Object, DefaultMutableTreeNode> nodes = new HashMap<Object, DefaultMutableTreeNode>();
              Iterator ii = values.keySet().iterator();
              while (ii.hasNext()) {
                   Object key = ii.next();
                   Object value = values.get(key);
                   if (nodes.containsKey(value)) {
                        DefaultMutableTreeNode node = nodes.get(value);
                        DefaultMutableTreeNode child = new DefaultMutableTreeNode(key);
                        node.add(child);
                   } else {
                        DefaultMutableTreeNode node = new DefaultMutableTreeNode(value);
                        DefaultMutableTreeNode child = new DefaultMutableTreeNode(key);
                        node.add(child);
                        nodes.put(value, node);
                        root.add(node);
              JTree tree = new JTree(root);Hope this helps,
    Alex.

  • Problem with JTree editing icons

    Hello,
    I want to edit another icons than the default icons in JTree object.
    I look in the javadoc at the several methods, but I do not find a method witch can give me the possibility to setup the collapsed and expanded icon.
    If some one now how to do that, it will be cool.
    Thanks.

    I write this class :
    public class SampleTreeCellRenderer extends TreeCellRenderer
    /** Font used if the string to be displayed isn't a font. */
    static protected Font defaultFont;
    /** Icon to use when the item is collapsed. */
    static protected ImageIcon collapsedIcon;
    /** Icon to use when the item is expanded. */
    static protected ImageIcon expandedIcon;
    /** Color to use for the background when selected. */
    static protected final Color SelectedBackgroundColor=Color.yellow;
    static
         try {
         defaultFont = new Font("SansSerif", 0, 12);
    } catch (Exception e) {}
         try {
         collapsedIcon = new ImageIcon("images/collapsed.gif");
         expandedIcon = new ImageIcon("images/expanded.gif");
         } catch (Exception e) {
         System.out.println("Couldn't load images: " + e);
    public SampleTreeCellRenderer() {
    super();
    public SampleTreeCellRenderer(String collapsedImagePath,String expandedImagePath) {
    super();
         try {
         if (collapsedImagePath!=null) collapsedIcon = new ImageIcon(collapsedImagePath);
         if (expandedImagePath!=null) expandedIcon = new ImageIcon(expandedImagePath);
         } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    public void setCollapsedIcon(String path) {
    try {
    if (path!=null) collapsedIcon=new ImageIcon(path);
    } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    public void setExpandedIcon(String path) {
    try {
    if (path!=null) expandedIcon=new ImageIcon(path);
    } catch (Exception e) { System.out.println("Couldn't load images: " + e); }
    /** Whether or not the item that was last configured is selected. */
    protected boolean selected;
    public Component getTreeCellRendererComponent(
    JTree tree, Object value,     
    boolean selected, boolean expanded,
    boolean leaf, int row, boolean hasFocus) {
         Font font;
         String stringValue = tree.convertValueToText(value, selected,expanded,leaf,row,hasFocus);
         /* Set the text. */
         setText(stringValue);
         /* Tooltips used by the tree. */
         setToolTipText(stringValue);
         /* Set the image. */
         if(expanded) { setIcon(expandedIcon); }
         else if(!leaf) { setIcon(collapsedIcon);}
    else { setIcon(null);}
         /* Update the selected flag for the next paint. */
         this.selected = selected;
         return this;
    public void paint(Graphics g) {
         super.paint(g);
    } // end of class SampleTreeCellRenderer
    I test it but I do not understand why it do not display the icons.

  • Problem with JTree

    Hi All,
    Can anyone please help me in writing a method which will take a JTree/TreeNode/MutableTreeNode and a string as parameters, and then search the JTree/TreeNode/MutableTreeNode for that particular string (which will be the name of a node/leaf in the tree), and then expand the JTree to show the node/leaf?
    Thanx a lot in advance,
    Best Regards,
    Debopam.

    Here's something:import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class Test extends JFrame {
        private TreePanel treePanel;
        public Test () {
            getContentPane ().setLayout (new BorderLayout ());
            getContentPane ().add (treePanel = new TreePanel ());
            getContentPane ().add (new SearchPanel (), BorderLayout.SOUTH);
            pack ();
            setDefaultCloseOperation (EXIT_ON_CLOSE);
            setLocationRelativeTo (null);
            setTitle ("Test");
            setVisible (true);
        public Dimension getPreferredSize () {
            return new Dimension (600, 600);
        private class TreePanel extends JPanel {
            private DefaultTreeModel model;
            private JTree tree;
            public TreePanel () {
                model = new DefaultTreeModel (createRoot ());
                tree = new JTree (model);
                tree.setRootVisible (false);
                tree.setShowsRootHandles (true);
                setLayout (new BorderLayout ());
                add (new JScrollPane (tree));
            private TreeNode createRoot () {
                DefaultMutableTreeNode root = new DefaultMutableTreeNode ("");
                add (root, 1, 3);
                return root;
            private void add (DefaultMutableTreeNode node, int i, int n) {
                for (int l = 0; l < 26; l ++) {
                    DefaultMutableTreeNode child = new DefaultMutableTreeNode (((String) node.getUserObject ()) + (char) ('a' + l));
                    if (i < n) {
                        add (child, i + 1, n);
                    node.add (child);
            public void searchAndExpand (String text) {
                TreeNode[] path = search ((DefaultMutableTreeNode) model.getRoot (), text);
                if (path != null) {
                    TreePath treePath = new TreePath (path);
                    tree.scrollPathToVisible (treePath);
                    tree.setSelectionPath (treePath);
            private TreeNode[] search (DefaultMutableTreeNode node, Object object) {
                TreeNode[] path = null;
                if (node.getUserObject ().equals (object)) {
                    path = model.getPathToRoot (node);
                } else {
                    int i = 0;
                    int n = model.getChildCount (node);
                    while ((i < n) && (path == null)) {
                        path = search ((DefaultMutableTreeNode) model.getChild (node, i), object);
                        i ++;
                return path;
        private class SearchPanel extends JPanel {
            public SearchPanel () {
                JTextField searchField = new JTextField (10);
                searchField.addActionListener (new ActionListener () {
                    public void actionPerformed (ActionEvent event) {
                        treePanel.searchAndExpand (((JTextField) event.getSource ()).getText ());
                setLayout (new GridBagLayout ());
                add (searchField, new GridBagConstraints ());
        public static void main (String[] parameters) {
            new Test ();
    }Kind regards,
      Levi

  • Problem with Jtree to xml tranform..how to set/get parent of a node?

    Hi,
    I am trying to develop xml import/export module.In import wizard, I am parsing the xml file and the display it in Jtree view using xml tree model which implements TreeModel and xml tree node.I am using jaxp api..
    It is workin fine.
    I got stuck with removal of selected node and save it as a new xml.
    I am not able to get parent node of selected node in remove process,itz throwing null.I think i missed to define parent when i load treemodel.Plz help me out..give some ideas to do it..
    thanks
    -bala
    Edited by: r_bala on May 9, 2008 4:44 AM

    there's no way anyone can help you without seeing your code.

  • Problem with JTree while expanding/collapsing a node

    Hi,
    I'm using a JTree for displaying the file system.
    Here, i want that whenever a node get expanded,
    it should show the latest files/directories under that node.
    Now, what i'm doing is, getting all the files/dir's using files.listFiles(),
    under that node and then creating a new node and adding it to parent (all in expand() method).
    But, now the problem is, while doing this whenever the parent node get expanded its adding all the latest files/dirs into the previous instance
    resulting the same file/dir is displaying twice,thrice.. and so on, as that node is expanded and collapsed.
    i tried removeAllChildren() in collapse() method but then that node is notexpanding at all .
    Can anybody help me please...
    i got stuck b'coz of this only.
    Thanks...

    Now what i'm doing is every time expand() get called,
    i'm comparing all the children of that node in the
    current instance with all the children present in the
    file system (because there is a possibility that some
    file/dir may be added or deleted)
    is this the right wy or not?it certainly is not wrong, but as usual, there is more than 1 way to implement this...
    b'coz right now i'm getting all the files/dirs that
    are newly added but facing some problem if somebody
    deletes a file/dir.
    i'm still trying to get the solutionthen you should not just compare all the children of the node with the files/dirs but also the other way round. compare the files/dirs with the children to determine if the file/dir still exists and if not remove the node.
    or you could check if the file which a node represents exists and if not remove the node.
    thomas

Maybe you are looking for