Question on JTree

Hi All,
I have a main root as VNVExecutor in JTree and one of its sub tree is User Manual.So i am seperating the whole with left component as JTree and Right Components as JScrollPane by using JSplitPane.Now my doubt is when i click on subtree component i.e. usermanual a JTextField/JButton..watever may be the component that has to be added.Can ay one help me out in telling how to perform this??
Thanks in advance.
regards,
Viswanadh

Read the Swing tutorial on [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html] for a working example. The example there disiplays text in a text area, so you would customize it to do what you want.

Similar Messages

  • Swing Gurus! A question abt JTREE??

    i have a jtree with nodes in it . when the user selects a node,
    a dialog box appears asking confirmation whether to he wants to exit the current function.
    If he clicks on "yes" it will do the necessary operation.
    Note:This dialog box doesn't appear when the user selects a node for the first time.
    Problem: When the user selects a node after selecting a node earlier,
    it is highlighted with blue color and then a confirmation dialog pops up.
    if he clicks on "NO" i want to revert back to the old node which was earlier
    selected and highlight the node.
    iam able to get the previous node but iam not able to highlight it.
    how to highlight the previous one?
    tks in advance!

    You can try
    tree.setSelectionRow(int row);
    All you have to do is keep track of the previous selected node index and when the user selects "No", use the method to re-select the previous node.
    I haven't tested this, but I am sure it will work...
    Good luck!

  • Leaf and JTree

    Hi all,
    I would like to ask a small question about JTree. Is there a way to not display leaf without removing them from the tree?
    Actually I used a tricky whay by crating my own DefaultTreeCellRenderer and checking when it's the leaf I set the preferedSize to 0. However, by using this tricky way i have some weird behaviour with scrollPane.
    Does anyone has an idea to not display leaf in a JTree?
    Regards,
    Raffael

    Raffael wrote:
    Hello,
    thanks for your anserw. However, creating your own JTreeModel allow you to specify if a node is a leaf or not. But you will not being able to not draw it via the tree model or I m wrong?Your custom TreeModel will have to 'hide' the leaf nodes from objects that ask about them. Here's an example that wraps a DefaultTreeModel:
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTree;
    import javax.swing.WindowConstants;
    import javax.swing.event.TreeModelListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeModel;
    import javax.swing.tree.TreePath;
    public class HiddenLeaves {
        HiddenLeaves() {
            JFrame f= new JFrame();
            f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
            DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
            DefaultMutableTreeNode nodeA = new DefaultMutableTreeNode("Node A");
            nodeA.add(new DefaultMutableTreeNode("Leaf One"));
            nodeA.add(new DefaultMutableTreeNode("Leaf Two"));
            nodeA.add(new DefaultMutableTreeNode("Leaf Three"));
            DefaultMutableTreeNode nodeB = new DefaultMutableTreeNode("Node B");
            nodeB.add(new DefaultMutableTreeNode("Leaf Four"));
            nodeB.add(new DefaultMutableTreeNode("Leaf Five"));
            nodeB.add(new DefaultMutableTreeNode("Leaf Six"));
            root.add(nodeA);
            root.add(nodeB);
            final FilteredTreeModel model = new FilteredTreeModel(new DefaultTreeModel(root));
            final JTree tree = new JTree(model);
            f.add(new JScrollPane(tree), BorderLayout.CENTER);
            JButton b = new JButton("Toggle Leaf Display");
            b.addActionListener(new ActionListener() {
                public void actionPerformed(ActionEvent ae) {
                    boolean visible = model.isShowingLeaves();
                    model.setShowingLeaves(!visible);
                    tree.repaint();
            f.add(b, BorderLayout.SOUTH);
            f.setSize(400,300);
            f.setVisible(true);
        public static void main(String[] args) {
            new HiddenLeaves();
        private static class FilteredTreeModel implements TreeModel {
            private boolean showingLeaves = true;
            private DefaultTreeModel delegate;
            public FilteredTreeModel(DefaultTreeModel delegate) {
                this.delegate = delegate;
            public void setShowingLeaves(boolean show) {
                this.showingLeaves = show;
                delegate.reload();
            public boolean isShowingLeaves() {
                return showingLeaves;
            public Object getChild(Object parent, int index) {
                Object child = delegate.getChild(parent, index);
                if (!isShowingLeaves() && delegate.isLeaf(child)) {
                    child = null;
                return child;
            public int getChildCount(Object parent) {
                int count = delegate.getChildCount(parent);
                if (!showingLeaves) {
                    int newCount = count;
                    for (int i = 0; i < count; i++) {
                        if (delegate.isLeaf(delegate.getChild(parent, i))) {
                            newCount--;
                    count = newCount;
                return count;
            public int getIndexOfChild(Object parent, Object child) {
                int index = delegate.getIndexOfChild(parent, child);
                if (!showingLeaves) {
                    if (delegate.isLeaf(child)) {
                        index = -1;
                return index;
            public Object getRoot() {
                return delegate.getRoot();
            public boolean isLeaf(Object node) {
                return delegate.isLeaf(node);
            public void valueForPathChanged(TreePath path, Object newValue) {
                delegate.valueForPathChanged(path, newValue);
            public void addTreeModelListener(TreeModelListener l) {
                delegate.addTreeModelListener(l);
            public void removeTreeModelListener(TreeModelListener l) {
                delegate.removeTreeModelListener(l);
    }

  • Allow right-click selection in a JTree

    Hi everybody! How are today? Fine? I hope so.
    I've got a little question about JTrees: i want to put a right-click popup menu on my JTree, which may not be the same depending on which node of the tree is selected.
    My problem is that i must do a left click selection of the node before doing the right click in order that this one may be effective and correct (i.e the correct popup menu appears).
    So, i want to allow the right click selection in my JTree to select the node and to perform the action linked to the Popup menu.
    I will be very thankfull if someone could help me :)

    Sorry to post twice, but just thought i'd post the code to show you what I mean (forgive me not making this entirely generic):
    ///// Some "global" variables:
         private JPopupMenu               stPopupMenu;
         private TreePath               stPath;
         private String                    stPathComponent;
         private int                         stCount;
         private Object                    selectedNode;
    ///// Attaching the listeners:
    symbolTreeDisplay.addTreeSelectionListener(stHandler);
    symbolTreeDisplay.addMouseListener(stHandler);
    //// The event listener class:
         private class SymbolTreeHandler extends MouseAdapter implements
                   TreeSelectionListener
              public void mouseClicked(java.awt.event.MouseEvent event)
                   try
                        if (event.getModifiers() == event.BUTTON3_MASK)
                        {//right button click on mouse
                             stPopupMenu = new JPopupMenu();
                             // add your logic here, based on selectedNode to add items to the menu
                             stPopupMenu.show(symbolTreeDisplay, event.getX(), event
                                       .getY());
                   catch (Exception e)
              public void valueChanged(TreeSelectionEvent aTreeEvent)
                   try
                        stPath = aTreeEvent.getPath();
                        stCount = stPath.getPathCount();
                        selectedNode = stPath.getPathComponent(stCount - 1);
                   catch (Exception e)
         }

  • JTree and JButton in node.

    Helo.
    I've a question regarding JTree component. I was wondering if it is possible at all.
    I want to build JTree component with JButton(JPanel) in each node, for example:
    RootNode
    |
    ---String [JButton][JButton]
    |
    ---String [JButton][JButton]
    Is there possibility to put JPanel into children node.
    Maybe anyone did do this before?
    Thanks in advance for any help.
    Regards

    This is possible. You'll have to take a look at TreeCellRenderer and TreeCellEditor, and maybe the tutorial at http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html . Basically, both interfaces allow you to return arbitrary components for rendering / editing tree nodes. The default implementation is based on JLabels, but you can use complex panels with multiple child components as well.

  • JTreeTable / TreeModel question

    Hi all,
    I have two questions about JTrees and TreeModels.
    I have an application which builds a TreeModel from an XML file, and displays it in a JTreeTable (see: http://java.sun.com/products/jfc/tsc/articles/treetable1/). There are two panels to display an XML file. The XML file consists of parameters which all have a name and a value:
    root
    |- header
    |  |- parameter1                value
    |  |- parameter2                value
    |  |- parameter3                value
    |- data
       |- parameter1                value
       |   |- parameter1.1          value
       |   |- parameter1.2          value
       |- parameter2                value
       |   |- parameter2.1          value
       |- parameter3                value
       |- parameter4                valueNow I want to compare two nodes (one from both panels). The user can select a node on both panels to compare.
    There are two tasks I want to implement:
    1) I want to compare the parameters without taking into account the order in which they appear. A parameter is considered different when it has the same parent, the same name, but a different value.
    2) I also want to separate those parameters which are unique for both trees (it doesn't appear in the other tree)
    Thus, if I want to compare a node from jtree1, I first need to find a corresponding node in jtree2. If I can't find it, it is unique in jtree1, else I can compare the values and decide if they are the same. But how can I check for the corresponding node in jtree2?
    There is also a second problem, how can I get the selected node from a JTreeTable? I tried with getSelectedIndex(), but when parameter1.1 is selected, the getSelectedIndex returns 7, while the root lement only has two child nodes... so getChildAt(index) will not work.

    You can accomplish what you are looking to do through the use of something called model filtering. I have published an article on it on IBM's website at http://www-106.ibm.com/developerworks/library/j-filters/?dwzone=java.
    I would direct you to the part that discusses 'exclusion filters' in particular. If you want to adapt this to the TreeModel architecture, it should be fairly simple.
    Mitch Goldstein
    Author, Hardcore JFC (Cambridge Univ Press)
    [email protected]

  • Question with updating JTree Display

    Hello all,
    I have a question about how to change what a JTree is displaying. Currently I have classes called ElementTreeFrame, ElementTree, ElementTreeModel, and, of course, Element. The ElementTreeFrame is simply the frame where I store a ElementTree, it has 2 buttons (JButtons at the bottom) Add and Open. I am trying to Dynamically add an Element to my ElementTree.
    The Element class has a Vector in it, called childElements. When the user clicks Add, a new Element is added to the Vector. Let me explain a bit further. The element that is currently selected is returned via
    parentElem = (Element)parentPath.getLastPathComponent();
    Then a new Element is added by saying
    parent.childElements.insertElementAt(child, parent.getChildCount());
    which is code the Vector class provides. parent.getChildCount() simply returns the number of children present so that the child (the new Element being added) can be inserted in the right place.
    Here is my problem. When I first add an Element, it works fine. As a matter of fact, I can add as many Elements as I want and it will work fine. That is, until I manually expand the tree. When an Element is added, the tree doesn't expand. So I can add as many as I want, and it will work fine. The instant I coudlbe click on my Element to expand the tree, I can no longer insert a new Element. Technically, it gets inserted correctly, I know this because getChildCount remains correct, but the display is no longer correct. The line that extends from the folder to the new leaf is broken.
    I need to find a way to refresh my tree display. I am at a complete loss on how to do this. I have read about firingTreeNodesInserted or using reload, or a bunch of other methods but I am confused due to an overload of different methods.
    Can anyone tell me what my train of thought should be to do this? I'd just like a simple way for the nodes to be displayed correctly.
    Thank you so much,
    Nick

    Neverrmind, I figured it out. A call to to eTree.updateUI() handled it just nice.
    Thanks to myself, for being so hot.

  • JTree sizing question...

    Hello:
    I have a JTree for which each cell contains a button. I have written a renderer that renders the button, and I realize that I have to do some special stuff to capture a click on the button. My question is unrelated to all of that.
    The problem is that over time, the labels on my buttons change (and may become longer (wider)), but the tree size does not change. In fact, when I update the button label and the tree is re-rendered the rendering of the button gets "chopped off". I've put the tree in a scroll pane, but this doesn't help - the right side of some of the buttons get cut off to the original tree size. I've tried lots of different variations on setPreferredSize, calling repaint, etc, and am not having any luck. I've put together a demonstration of this behavior in a smallish application that I'm posting here, where I create a 2 node tree with buttons that read "Hi", then I change the button labels to "Goodbye" and re-render. You'll see that the button's are cut off about halfway through the button.
    In case its important - I'm running java version 1.5.0_07 on a 32-bit Linux box.
    Any help would be greatly appreciated. Thanks in advance!
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.awt.*;
    public class JTreeQuestion
      public static void main(String [] args)
        JTreeFrame f = new JTreeFrame();
        f.pack();
        f.setLocation(30, 30);
        //Draws buttons with "Hi" (short string)
        f.setVisible(true);
        ButtonNode.updateString("Goodbye");
        //Draws buttons with longer string, buttons get "cut off"
        f.repaint();
    class JTreeFrame extends JFrame
      JTree tree;
      JScrollPane treeView;
      public JTreeFrame()
        super("My Tree");
        DefaultMutableTreeNode root;
        root = new DefaultMutableTreeNode(new ButtonNode());
        root.add(new DefaultMutableTreeNode(new ButtonNode()));
        tree = new JTree(root);
        tree.setCellRenderer(new ButtonNodeRenderer());
        treeView = new JScrollPane(tree);
        add(treeView);
    class ButtonNode
      public static String str = "Hi";
      public static void updateString(String inStr)
      { str = inStr; }
      String getStr()
      { return str; }
    class ButtonNodeRenderer extends DefaultTreeCellRenderer
      public Component getTreeCellRendererComponent(JTree tree,
                              Object value, boolean sel, boolean expanded,
                              boolean leaf, int row, boolean hasFocus)
        Box theBox = new Box(BoxLayout.X_AXIS);
        super.getTreeCellRendererComponent(tree, value, sel, expanded,
                                           leaf, row, hasFocus);
        DefaultMutableTreeNode jtreeNode = (DefaultMutableTreeNode)value;
        theBox.add(new JButton(((ButtonNode)jtreeNode.getUserObject()).getStr()));
        return (theBox);
    }

    For those who are interested. The DefaultTreeModel has a method named nodeChanged() that tells the tree model that a specific node has changed, and the model re-interprets the cell causing its sizse to change as necessary, so that the full button is rendered now.
    Basically what I did was instead of calling repain, I call a method that I wrote that loops through all the tree nodes, indicates they have changed, then repaint's, and it all works out. My trees are relatively small, so this is fine, but if others face the same problem, you'll probably want to selectively indicate which nodes have changed so the tree model doesn't have to do more work than necessary.

  • JTree image question

    I have a question about using images in a JTree.
    I have like 2 parent nodes who both have a lot of child nodes now i know how to get an image for every node but how do i get 1 image for 1 parent with all his children and another image for the other parent with his children.

    It is a programming problem because i dont know how to give echt DefaultMutableTreeNode his own picture. You should think of it like msn when you log in your contacts are in a Tree and your offline contacts have a red icon and online contacts have green one. I need to to the same for my program(chat program). But i can't figure out how but i know how to give alle the DefaultMutableTreeNode's a picture but i cant give individual one's a picture.
    I hope i cleared things up :)

  • JTree#expandRow() Question

    JTree tree;
    //etc...
    1) /** Expand the tree */
    for (int i=0; i<tree.getRowCount(); i++)
         tree.expandRow(i);
    and tree.getRowCount() = 6
    2) /** Expand the tree */
    for (int i=0; i<6; i++)
         tree.expandRow(i);
    My tree has 6 rows, and each row has its own sub-tree hierarchy.
    I wonder why the first case will expand the whole tree, which includes
    the subtrees of each row.
    But in second case, it only expands the first 6 rows in the tree.
    So basically the question is why (1) and (2) have different tree view outputs??

    Well, after you expand row 1, the row count isn't 6 anymore, is it? It's something larger than that, depending on how many children the first node has.

  • JTree Updating question

    Hi there. I have two questions.
    I have a data structure that is being displayed in a JTree, so I made a Model and it works great. The data structure can be updated from non-gui interaction. The nodes don't change position or anything, its just the data that is displayed is changed. I handle it currently by calling a function in the model I made called nodesChanged(), which basically does the following:
    public void nodesChanged()
        int len = treeModelListeners.size();
        TreeModelEvent e = new TreeModelEvent(this, new Object[] {rootItem});
        for (int i = 0; i < len; i++) {
          ( (TreeModelListener) treeModelListeners.elementAt(i)).treeNodesChanged(e);
      }It does actually work, the changes are reflected in the JTree, but it seems a little expensive, and the updates to the actual data model could come at about 150 per second. To deal with that now, I just use a timer class that updates it about every 3/10's of a second, which does a pretty good job, but is there a more elegant way to do this? Something where the node is an observer of the data in the data structure (which are Observable objects)?
    The second question I have is when I do the above, sometimes the display name of the node will be larger than the value it had previously, but the Textbox (if that's what it is) doesn't grow, so I get a ... at the end.
    For example, if I have "Run" and it changes to "Stopped", it will show up as "Sto...".
    Any help would be great. TIA.

    well, you can start by making the node you put in the tree model event the lowest node in the tree that needs updating, instead of root.
    I don't know about the timer thing, cuz as far as I know, the listener will invoke code that will refresh the renderers, as opposed to painting where repaint calls can be merged into one. If you aren't getting that many updates all the time, you could implement something where the listener fires to an intermediate listener which will fire the info to the tree after a slight delay. That way if you get multiple updates, you can effectively ignore lots of them.
    The ... thing, I thought that treeNodesChanged was the appropriate method, although maybe it has to be for the specific node, not root.

  • JTree questions (1) Re-populating (2) Adding popups

    Hi all,
    I've just started to use a JTree in my application and I've encountered two
    problems. Sorry if these have been covered before - I've been Googling around
    for answers.
    I have a UI panel ...
    http://photos1.blogger.com/blogger/541/411/1600/TreeDemo.gif
    ... where a tree is populated with stock quotes from different
    sources. The user selects the stock and the tree should update to show the
    quotes for that stock. The quotes are read from a DB and I want the user to
    be able to delete from the DB using a pop-up on the leaf nodes.
    Problems
    (1) Re-populating
    The only way I've got this to work at this time is to create a new tree from scratch,
    based on the stock name, then put it into a new scroll panel, remove the old scroll
    panel from the container and add the new one. Not good is it? Nasty, nasty.
    I've read a lot about needing to interact with the tree model - is that right?
    (2) Adding popups
    I want to be able to delete items from the DB by doing a right-click on the leaf
    nodes and selecting "Delete" from the pop-up.
    I find that I can't add a mouse listener to the DefaultMutableTreeNode used to
    hold the leaf item. Should I subclass DefaultMutableTreeNode and implement some
    interface to do this?
    Any insights very much appreaciated.

    I know I'm asnwering my own question here - but I found the answer to teh re-population question while waiting.
    I now use the DynamicTree class that is included in the Sun tutorial here
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    Specifically, here
    http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/index.html#DynamicTreeDemo
    I'd still welcome any suggestions on the pop-up menu question!

  • Confused -  jTree Questions

    Hi
    I have looked through the forum and other articles for answers to my questions but I am still confused.
    In my SWING application I have a JTree which has Node Type binding on it and displays nodes corresponding to Master and Detail views.
    What is the best way to capture the value of selected Node that is after a button is clicked?
    Secondly what is the best way to create an empty unbinded JTree (When i try to add a JTree the default nodes such as colors, sports etc show up)?
    What is the best way to populate this JTree? (The new JTree will be populated using the selected values from the first JTree after a button is clicked.)
    Any help will be apreciated. I have no clue where to proceed.
    Thanks in advance

    See:
    http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
    Frank

  • JTree and selected node question

    Hello
    Is it possible to convert the selected node to an int?
    I guess I'm looking for something llike this.
    int nodeNumber = node.getSelectedIndex();
    There is nothing like that in the API, and it would help greatly if I could find a way do this.
    Thanks
    Have a good holiday
    Jim

    From the API for JTree
    public int getMinSelectionRow()
    Gets the first selected row.
    Returns:
    an integer designating the first selected row, where 0 is the first row in the display
    But I think this is based on how many rows are displayed at the present time and might change if the tree is opened above it.

  • JTree custom cell renderer question

    When using a custom cell renderer is their anyway to tell the offset of the current node?
    For example if you have a tree with the parent node "Parent" that has a few children nodes it will look something like this:
    Parent
    |----Child 1
    |----Child 2
    |----Child 3
    So the parent would have an offset of zero. I want to know how to get the childrens offset? If this is possible?
    What I am trying to accomplish:
    I have a JTree as a scrollpane rowHeader. While the main body of the scrollpane is a JTable. I need the tree's nodes to fill the entire width so that it looks like part of the table. I figure the row header width - current node offset should be the width that I will need each node to be. Any help is welcome. Thanks.

    the renderer tells you the row, the tree can get you a treepath for a row
    TreePath getPathForRow(int row)
    That can tell you the depth of the node.

Maybe you are looking for

  • 24"LED and a Power Mac G5

    Is it possible to connect a 24" LED display to my Power Mac G5? Thanks in advance for any help.

  • RAID best practice on UCS C210 M2

    H everyone, I  have a C210 M2 Server with LSI MegaRAID 9261-8i Card with 16 hard  drives of each 146GB. If I am going to run CUCM, CUC and CUPS to support up to 5000 users, What is the best practice to configure virtual drives? Do I need any hot spar

  • Exchange 2013 SP1: Fix for failing MSExchangeTransport service

    We had a newly updated Exchange 2013 SP1 that would not start the Transport service "Netstat -b" showed that a service was listening to port 25 on all IP's (0.0.0.0:25) and when the service could not get the port, it would die, and Exchange would att

  • Gl balance on day  basis

    Hi freinds, If  I want to see GL Balance On day  or on particular date basis form which T-code I can get this.

  • How to generate an in-sync sinusoid?

    I want to generate a sinusoid which will track (with a fixed phase shift) an externally monitored sinusoid.  The signal of interest is a sinusoid of less than 10kHz.  I've heard rumblings of FFTs, PLLs, measuring zero-crossings, etc.  Has anyone done