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));
}

Similar Messages

  • How to highlight JTree node without selecting it

    Hello,
    I want to highlight a Tree Node without selecting it.
    Anybody having ideas as to how i can do it.
    thanks in advance.
    Reg,
    sai

    for what it's worth for anyone with the same problem, the problem was that the node was being regenerated as a different object so each time it went through the object wasn't the same and therefore had a new expanded value as default of false.

  • How do i expand all the nodes in a jtree

    Hi,
    I am working on a project where i need to expand all the nodes of a jtree i have tried a few different ways but it never seems to expand all the nodes..
    I would be very greatful if someone could point me in the right direction
    cheers
    Mary

    you could use the following method that expands nodes recursively
    expandNode( myTree, myRootNode, new TreePath( myRootNode ) );
    public static void expandNode( JTree tree, TreeNode node, TreePath path ) {
        tree.expandPath( path );
        int i = node.getChildCount( );
        for ( int j = 0; j< i; j++ ) {
            TreeNode child = node.getChildAt( j );
            expandNode( tree, child , path.pathByAddingChild( child ) );
    }

  • JTree node incorrectly becomes a leaf after collapse?

    Hi all,
    I'm trying to fix a bug in a JTree where a node spuriously turns into a leaf after the user collapses it, and I'm beginning to wonder whether it's my code that's at fault or something within Java (The project uses JDK 1.3.1.06 - I cannot change this part!)
    The problem is as follows. The user expands the tree and selects a leaf. He or she then clicks the collapse icon of a node somewhere in the path to that leaf. (that node can be the parent, grandparent, great-grandparent or any other node, right up to the root.) The node collapses, but the expand icon is not displayed beside the collapsed node, and double-clicking does not cause the node to expand. In other words, the node now looks like a leaf.
    The problem does not occur if the user collapses the node by double-clicking on the node, or if an non-leaf node was selected.
    My swing knowledge is not that extensive, so I was wondering whether this was a known bug, or whether anyone can think of some obvious mistake I might be making...
    /Michael

    HI,
    Is the node which is becoming leaf do have some childrens?
    If not than checkout while creating object of DefaultMutableTreeNode did u specified have its allowsChildren property to false.
    In case your case is different from above. Than you might have encountered some bug in JTree, which you can report at following URI.
    http://java.sun.com/webapps/bugreport/
    Cheers
    -Hemant

  • How to Dinamicaly load-save JTree nodes ?

    Hi !
    A have one program. Use 1 JTree with a lot of nodes. (200.000-1.000.000. is much)
    For every node store is sored 7-8 boolan variables, 2long, and 5-6 String variables, whitch legth is 3-20. (Not much).(Information about files avaible somevhere)
    Now I save the root node(or the treeModel ) with ObjectOutputStream and load with ObjectinputStream. It generates 10-45Mb. I can export to XML but need about 350Mb memory to construct the DOM.an dthe Savad xml is 90Mb. It take long time to load, take a lot of memory.
    But don`t need to be stored all in the sytem memory. It is enugth to be stored one node, and after the user select that node load information about chilld nodes from the stored file and construct the child nodes, if the child node is selected(or try to be expanded) load information from file again.
    I think it is an idea to store somehow key-values but with PropertiesResourceBundle it is slow again. How is posible to store my data?
    Can you help me to store data dinamicaly in file and read from that?.

    How is posible to store my data?This is the real question, isn't it? Not how to load and save them, that comes later.
    You give each node an arbitrary identifier. A number works well. Then create a database table where you store the node identifier, the node's parent identifier, and the various information that belongs to the node. (If the node is the root node, store NULL as its parent).
    Then, to load the root node, find the database row whose "parent" column is NULL. Read that, make a node out if it, and set it as the root of your tree. To load the children of a node (you'd do this in a TreeWillExpandListener if I remember the name correctly) you find the database rows whose "parent" column is the node that is expanding. Read them, make nodes out of them, and add them as children to that node.
    There's more to it than that, of course, but that should be a start, I hope.

  • Can not highlight a JTree node programmatically

    Hi Swing lovers,
    I can select a node using setSelectionPath. Unfortunately I can not find a way to show the user that the node is selected. I know it can be done. When traversing the tree with the up- and down keyboard arrow, it shows what I want to see.
    Am I overlooking some method here?
    Thanks a lot for the tip,
    Erik

    Thanks DrClap,
    I expected to find an easy way to mark a jTree node as being selected. However the TreeCellRenderer does the job. See the code snipped below:
    public JTree jTree1 = new JTree();
    private TreeNode currentNode = null;
    //assing currentNode somewhere in you code
    jTree1.setCellRenderer(new MyRenderer());
    private class MyRenderer extends DefaultTreeCellRenderer {
        public MyRenderer() {
        public Component getTreeCellRendererComponent(
                                JTree tree,
                                Object value,
                                boolean sel,
                                boolean expanded,
                                boolean leaf,
                                int row,
                                boolean hasFocus) {
          if (currentNode != null) {
            if (value.hashCode() == currentNode.hashCode()) sel = true;
        super.getTreeCellRendererComponent(
                                tree, value, sel,
                                expanded, leaf, row,
                                hasFocus);
        return this;
    /

  • JTree - full row select

    Hi,
    I would like to make the JTree tree items selectable/appearing like in the eclipse "Package Explorer". A tree item should become selected when the user clicks anywhere in it's row. Additionally the background color of the full row should be the selection-background color not only the label background.
    Any ideas how to do this ? I hope there is a solution for this, but I have doubts about it because of how the CellRenderer thing works.
    Thanks in advance,
    Christian

    Hi
    The mouse listener in that solution doesn't properly handle SHIFT/CTRL.
    This should work better:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Insets;
    import java.awt.Rectangle;
    import java.awt.event.MouseAdapter;
    import java.awt.event.MouseEvent;
    import javax.swing.UIManager;
    import javax.swing.plaf.basic.BasicTreeUI;
    import javax.swing.tree.TreePath;
    public class ExplorerTreeUI extends BasicTreeUI {
        private Color backgroundSelectionColor = null;
        private RowSelectionListener sf = new RowSelectionListener();
        protected void installDefaults() {
            super.installDefaults();
            backgroundSelectionColor = UIManager.getColor("Tree.selectionBackground");
        protected void paintRow(Graphics g, Rectangle clipBounds,
                Insets insets, Rectangle bounds, TreePath path,
                int row, boolean isExpanded,
                boolean hasBeenExpanded, boolean isLeaf) {
            // Don't paint the renderer if editing this row.
            if (editingComponent != null && editingRow == row)
                return;
            if (tree.isRowSelected(row)) {
                int h = tree.getRowHeight();
                g.setColor(backgroundSelectionColor);
                g.fillRect(clipBounds.x, h*row, clipBounds.width, h);
            super.paintRow(g, clipBounds, insets, bounds, path, row, isExpanded,
                    hasBeenExpanded, isLeaf);
        protected void installListeners() {
            super.installListeners();
            tree.addMouseListener(sf);
        protected void uninstallListeners() {
            tree.removeMouseListener(sf);
            super.uninstallListeners();
        private class RowSelectionListener extends MouseAdapter {
                         * Listener for selecting the entire rows.
                         * @author Kirill Grouchnikov
            @Override
            public void mousePressed(MouseEvent e) {
                if (!tree.isEnabled())
                    return;
                TreePath closestPath = tree.getClosestPathForLocation(e.getX(), e.getY());
                if (closestPath == null)
                    return;
                Rectangle bounds = tree.getPathBounds(closestPath);
                // Process events outside the immediate bounds -
                // This properly handles Ctrl and Shift
                // selections on trees.
                if ((e.getY() >= bounds.y)
                        && (e.getY() < (bounds.y + bounds.height))
                        && ((e.getX() < bounds.x) || (e.getX() > (bounds.x + bounds.width)))) {
                    // fix - don't select a node if the click was on the
                    // expand control
                    if (isLocationInExpandControl(closestPath, e.getX(), e.getY())) {
                        return;
                    selectPathForEvent(closestPath, e);
    }

  • 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.

  • Xml in JTree: how to not collpase JTree node, when renaming XML Node.

    Hi.
    I'm writing some kind of XML editor. I want to view my XML document in JTree and make user able to edit contents of XML. I made my own TreeModel for JTree, which straight accesses XML DOM, produced by Xerces. Using DOM Events, I made good-looking JTree updates without collapsing JTree on inserting or removing XML nodes.
    But there is a problem. I need to produce to user some method of renaming nodes. As I know, there is no way to rename node in w3c DOM. So I create new one with new name and copy all children and attributes to it. But in this way I got a new object of XML Node instead of renamed one. And I need to initiate rebuilding (treeStructureChanged event) of JTree structure. Renamed node collapses. If I use treeNodesChanged event (no rebuilding, just changes string view of JTree node), then when I try to operate with renamed node again, exception will be throwed.
    Is there some way to rename nodes in my program without collpasing JTree?
    I'am new to Java. Maybe there is a method in Xerces DOM implementation to rename nodes without recreating?
    Thanks in advance.

    I assume that "rename" means to change the element name? Anyway your question seems to be "When I add a node to a JTree, how do I make sure it is expanded?" This is completely concerned with Swing, so it might have been better to post it in the Swing forum, but if it were me I would do this:
    1. Copy the XML document into a JTree.
    2. Allow the user to edit the document. Don't attempt to keep an XML document or DOM synchronized with the contents of the JTree.
    3. On request of the user, copy the JTree back to a new XML document.
    This way you can "rename" things to the user's heart's content without having the problem you described.

  • How to show a jtable created when a tree node is selected in a jsplit pane

    hello,
    does anyone know how you would go about updating a jtable you have created in a split pane when the data of the jtable changes?
    i have a jtree that creates a jtable when a node is selected. i want to display this jtable in a split pane that is created when the gui is launched.
    any help appreciated. i know it has something to do with updating a table model but if anyone has any sample code of how to do this, could they post it?
    thank you.

    Hi Laura,
    When you make a selection on your JTree, what data are you send to the JTable? Is it an entirely new TableModel that gets set each time?
    If you don't already have an implementation, consider using one JTable and simply swap the models in and out on JTree selection. It's probably best to contain the JTable in JScrollPane also. Perhaps not necessary, but calls to revalidate and repaint on the JTable after setting whatever data it is you set should update what is displayed.
    Warm regards,
    Darren

  • Jtree node refuses to collapse upon clicking handle; makeVisible() was used

    Hello,
    While creating a new node and inserting as a leaf in the JTree, I use tree.makeVisible(newTreePath) to expand the new node and make visible. (Using expandPath() will not expand if a leaf was added).
    However now the jtree node refuses to collapse upon clicking the node handle.
    How do I get it to not insist on staying open - be able to collapse manually?
    thanks,
    Anil

    This is the JNI forum. I don't believe your post fits.
    then
    can I correctly assume that any class that
    "implements Cloneable" will handle making either a
    "shallow" or "deep" ... or even "semi-shallow" clone,
    respective to the class context .. right?
    It probably does something. The implementor might not have implemented anything though. And you have no idea what they implemented.
    No idea about your other question.
    You might want to think carefully about why you are cloning though.

  • Parse and display xml doc when click on JTree node?

    Ok so here is the code that I have now. You will have to make alot of html files to run the program, but they can be empty for now. What you can do is just put the same exact html file to be displayed in each node element. for example.
    DefaultMutableTreeNode n1_node1_b1 =
                        new DefaultMutableTreeNode(new ModuleInfo("Device", "device.html"));could be changed to
    DefaultMutableTreeNode n1_node1_b1 =
                        new DefaultMutableTreeNode(new ModuleInfo("Device", "status.html"));And just keep adding the status.html page to each one of the nodes.
    anyway.
    For now when I click on the node, the html file is displayed in the JScrollPane rPane = new JScrollPane(htmlPane); and the htmlPane is a JEditorPane
    what I need it to do.
    When I click on the JTree node. I would like to go out to an xml file, parse the information in it, and display it to the pane.
    I will need to later, be able to add, edit, or delete information on the xml through the pane later.
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import javax.swing.JTree;
    import javax.swing.JPanel;
    import javax.accessibility.*;
    import javax.swing.UIManager;
    import javax.swing.JComponent;
    import javax.swing.JEditorPane;
    import javax.swing.tree.TreeSelectionModel;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.ImageIcon;
    import java.net.URL;
    import java.io.IOException;
    import java.awt.Dimension;
    * @author orozcom
    public class Example extends JFrame implements TreeSelectionListener
        private JEditorPane htmlPane;
        private URL helpURL;
        private static boolean DEBUG = false;
        private JTree tree;
        public Example()
            super("Example");
            setSize(1200,900);
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            JMenuBar jmb = new JMenuBar();
            JMenu fileMenu = new JMenu("File");
            JMenuItem openItem = new JMenuItem("Open");
            JMenuItem saveItem = new JMenuItem("Save");
            JMenuItem exitItem = new JMenuItem("Exit");
            exitItem.addActionListener(new ActionListener()
                public void actionPerformed(ActionEvent ae)
                    System.exit(0);
            fileMenu.add(openItem);
            fileMenu.add(saveItem);
            fileMenu.add(new JSeparator());
            fileMenu.add(exitItem);
            jmb.add(fileMenu);
            setJMenuBar(jmb);
            //  **************** start JTree ******************//       
            JPanel lPane =new JPanel();       
            lPane.setLayout(new BorderLayout());
            DefaultMutableTreeNode top = new DefaultMutableTreeNode(new ModuleInfo("Devices","splashScreen.html"));
            DefaultMutableTreeNode branch1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Module 1", "module1.html"));
            DefaultMutableTreeNode branch2 =
                    new DefaultMutableTreeNode(new ModuleInfo("Module 2", "module2.html"));
            //DefaultMutableTreeNode branch3 =
                    //new DefaultMutableTreeNode(new ModuleInfo("Module 3", "module3.html"));
            //adding to the topmost node
            top.add(branch1);
            top.add(branch2);
            //top.add(branch3);
             *          BRANCH 1           *
            //adding to the First branch
            DefaultMutableTreeNode node1_b1
                    =new DefaultMutableTreeNode(new ModuleInfo("Status", "status.html"));
            //branch1.add(node1_b1);
                DefaultMutableTreeNode n1_node1_b1 =
                        new DefaultMutableTreeNode(new ModuleInfo("Device", "device.html"));
                DefaultMutableTreeNode n2_node1_b1 =
                        new DefaultMutableTreeNode(new ModuleInfo("Network", "network.html"));
                DefaultMutableTreeNode n3_node1_b1 =
                        new DefaultMutableTreeNode(new ModuleInfo("Chassis", "chassis.html"));
                DefaultMutableTreeNode n4_node1_b1 =
                        new DefaultMutableTreeNode(new ModuleInfo("Resources", "resources.html"));
                node1_b1.add(n1_node1_b1);
                node1_b1.add(n2_node1_b1);
                node1_b1.add(n3_node1_b1);
                node1_b1.add(n4_node1_b1);    
            DefaultMutableTreeNode node2_b1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Project Editor", "projedit.html"));
            DefaultMutableTreeNode node3_b1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Project Manager", "projmngt.html"));
            DefaultMutableTreeNode node4_b1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Administration", "administration.html"));
            DefaultMutableTreeNode n1_node4_b1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Device", "device.html"));
            DefaultMutableTreeNode n2_node4_b1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Network", "network.html"));
            DefaultMutableTreeNode n3_node4_b1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Users", "users.html"));
            node4_b1.add(n1_node4_b1);
            node4_b1.add(n2_node4_b1);
            node4_b1.add(n3_node4_b1);
            DefaultMutableTreeNode node5_b1 =
                    new DefaultMutableTreeNode(new ModuleInfo("Logging", "logging.html"));
            branch1.add(node1_b1);
            branch1.add(node2_b1);
            branch1.add(node3_b1);
            branch1.add(node4_b1);
            branch1.add(node5_b1);
             *          BRANCH 2           *
            //adding to the Second branch
            DefaultMutableTreeNode node1_b2 =
                    new DefaultMutableTreeNode(new ModuleInfo("Status", "status.html"));
                DefaultMutableTreeNode n1_node1_b2 =
                        new DefaultMutableTreeNode(new ModuleInfo("Device", "device.html"));
                DefaultMutableTreeNode n2_node1_b2 =
                        new DefaultMutableTreeNode(new ModuleInfo("Network", "network.html"));
                DefaultMutableTreeNode n3_node1_b2 =
                        new DefaultMutableTreeNode(new ModuleInfo("Chassis", "chassis.html"));
                DefaultMutableTreeNode n4_node1_b2 =
                        new DefaultMutableTreeNode(new ModuleInfo("Resources", "resources.html"));
                node1_b2.add(n1_node1_b2);
                node1_b2.add(n2_node1_b2);
                node1_b2.add(n3_node1_b2);
                node1_b2.add(n4_node1_b2);
            DefaultMutableTreeNode node2_b2=
                    new DefaultMutableTreeNode(new ModuleInfo("Project Editor", "projedit.html"));
            DefaultMutableTreeNode node3_b2=
                    new DefaultMutableTreeNode(new ModuleInfo("Project Manager", "projmngt.html"));
            DefaultMutableTreeNode node4_b2=
                    new DefaultMutableTreeNode(new ModuleInfo("Administration", "administration.html"));
                DefaultMutableTreeNode n1_node4_b2=
                        new DefaultMutableTreeNode(new ModuleInfo("Device", "device.html"));
                DefaultMutableTreeNode n2_node4_b2=
                        new DefaultMutableTreeNode(new ModuleInfo("Network", "network.html"));
                DefaultMutableTreeNode n3_node4_b2=
                        new DefaultMutableTreeNode(new ModuleInfo("Users", "users.html"));
                node4_b2.add(n1_node4_b2);
                node4_b2.add(n2_node4_b2);
                node4_b2.add(n3_node4_b2);
            DefaultMutableTreeNode node5_b2=
                    new DefaultMutableTreeNode(new ModuleInfo("Logging", "logging.html"));
            branch2.add(node1_b2);
            branch2.add(node2_b2);
            branch2.add(node3_b2);
            branch2.add(node4_b2);
            branch2.add(node5_b2);
             *          BRANCH 3           *
            //adding to the Third branch
            DefaultMutableTreeNode node1_b3=new DefaultMutableTreeNode("Status");
            DefaultMutableTreeNode n1_node1_b3=new DefaultMutableTreeNode("Device");
            DefaultMutableTreeNode n2_node1_b3=new DefaultMutableTreeNode("Network");
            DefaultMutableTreeNode n3_node1_b3=new DefaultMutableTreeNode("Chassis");
            DefaultMutableTreeNode n4_node1_b3=new DefaultMutableTreeNode("Resources");
            node1_b3.add(n1_node1_b3);
            node1_b3.add(n2_node1_b3);
            node1_b3.add(n3_node1_b3);
            node1_b3.add(n4_node1_b3);
            DefaultMutableTreeNode node2_b3=new DefaultMutableTreeNode("Project Editor");
            DefaultMutableTreeNode node3_b3=new DefaultMutableTreeNode("Project Manager");
            DefaultMutableTreeNode node4_b3=new DefaultMutableTreeNode("Administration");
            DefaultMutableTreeNode n1_node4_b3=new DefaultMutableTreeNode("Device");
            DefaultMutableTreeNode n2_node4_b3=new DefaultMutableTreeNode("Network");
            DefaultMutableTreeNode n3_node4_b3=new DefaultMutableTreeNode("Users");
            node4_b3.add(n1_node4_b3);
            node4_b3.add(n2_node4_b3);
            node4_b3.add(n3_node4_b3);
            DefaultMutableTreeNode node5_b3=new DefaultMutableTreeNode("Logging");
            branch3.add(node1_b3);
            branch3.add(node2_b3);
            branch3.add(node3_b3);
            branch3.add(node4_b3);
            branch3.add(node5_b3);
            tree=new JTree(top,true);
            //tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
            tree.getSelectionModel().setSelectionMode(TreeSelectionModel.CONTIGUOUS_TREE_SELECTION);
            //Set the icon for leaf nodes.       
            ImageIcon deviceIcon = createImageIcon("/device.gif");       
            if (deviceIcon != null)
                DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
                renderer.setLeafIcon(deviceIcon);
                tree.setCellRenderer(renderer);
            else
                System.err.println("Leaf icon missing; using default.");
            //Listen for when the selection changes.
            tree.addTreeSelectionListener(this);
            //Create the scroll pane and add the tree to it.
            //JScrollPane treeView = new JScrollPane(tree);
            tree.setToolTipText(" and ");
            lPane.add(tree);
            getContentPane().add(lPane);
            //  ****************  end  JTree  ******************//
            htmlPane = new JEditorPane();
            htmlPane.setEditable(false);       
            initHelp();
            JScrollPane rPane = new JScrollPane(htmlPane);
            JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, lPane, rPane);
            jsp.setDividerLocation(180);
            getContentPane().add(jsp, BorderLayout.CENTER);
            JPanel bPane = new JPanel();
            JButton okButton = new JButton("Ok");
            JButton applyButton = new JButton("Apply");
            JButton clearButton = new JButton("Clear");
            bPane.add(okButton);
            bPane.add(applyButton);
            bPane.add(clearButton);
            getContentPane().add(bPane, BorderLayout.SOUTH);
            setVisible(true);
        /** Required by TreeSelectionListener interface. */
        public void valueChanged(TreeSelectionEvent e)
            DefaultMutableTreeNode node = (DefaultMutableTreeNode)
            tree.getLastSelectedPathComponent();
            if (node == null) return;
            Object nodeInfo = node.getUserObject();
            if (node.isLeaf())
                ModuleInfo module = (ModuleInfo)nodeInfo;
                displayURL(module.moduleURL);
                if (DEBUG)
                    System.out.print(module.moduleURL + ":  \n    ");
            else
                displayURL(helpURL);
            if (DEBUG)
                System.out.println(nodeInfo.toString());
        private class ModuleInfo
            public String deviceName;
            public URL moduleURL;
            public ModuleInfo(String device, String filename)
                deviceName = device;
                moduleURL = (URL)Example.class.getResource("/" + filename);
                if (moduleURL == null)
                    System.err.println("Couldn't find file: "
                            + filename);
            public String toString()
                return deviceName;
        private void initHelp()
            String s = "YFDemoHelp.html";
            helpURL = Example.class.getResource("/" + s);
            if (helpURL == null)
                System.err.println("Couldn't open help file: " + s);
            else if (DEBUG)
                System.out.println("Help URL is " + helpURL);
            displayURL(helpURL);
        private void displayURL(URL url)
            try
                if (url != null)
                    htmlPane.setPage(url);
                else
                { //null url
                    htmlPane.setText("File Not Found");
                    if (DEBUG)
                        System.out.println("Attempted to display a null URL.");
            catch (IOException e)
                System.err.println("Attempted to read a bad URL: " + url);
        /** Returns an ImageIcon, or null if the path was invalid. */
        protected static ImageIcon createImageIcon(String path)
            java.net.URL imgURL = Example.class.getResource(path);
            if (imgURL != null)
                return new ImageIcon(imgURL);
            else
                System.err.println("Couldn't find file: " + path);
                return null;
        public static void main(String args[])
            new Example();
            //new AssistiveExample();
    }Thanks orozcom

    yes i can at the time of MIRO u can see both
    go in SU01 for and user
    in Parameters enter IVFIDISPLAY in Parameter ID and X in Paramater Value
    thus for that user u will be able to c Invoice number and accounting number after saving MIRo
    u will get message like
    Invoice document 5105608893 was posted ( Accountng Documnt: 5100000000 )
    hope this helps

  • Set different color for one JTree node

    hello,
    I managed to find how to set a color for Jtree nodes but the problem is that with my method all the nodes will b the same color whereas i'm looking to have nodes of different color depending on the situation.
    the method for setting all Jtree nodes the same color(other than black):
    tree.setCellRenderer(
    new DefaultTreeCellRenderer() {
       public Color getTextNonSelectionColor() {
         return Color.lightGray; } });I WANT TO CHOSSE EACH COLOR FOR EACH NODE
    help plz
    thanks

    You need to implement TreeCellRenderer interface
    public Component getTreeCellRendererComponent(JTree tree,
                                                  Object value,
                                                  boolean sel,
                                                  boolean expanded,
                                                  boolean leaf,
                                                  int row,
                                                  boolean hasFocus)You can know which node is rendering by check value argument. Please read DefaultTreeCellRenderer's code.

  • Urgent..Please..setting node as selected programmatically

    Hi,
    Can somebody tell me how to set a tree node as selected programmatically?..
    i.e. I have tree in which all the nodes bear a name of the color. I have a thread which keeps changing the selected node, and based on the selection the color will be displayed in my right panel.(JSplitPane). This should happen automatically and user will keep seeing the node selection changed in the tree and corresponding color in the right side. I have used DefaultTreeModel to loop thro' the tree nodes. But I am unable to make a node as selected in the tree..Can anyone help me please..Its urgent..
    Thanx in advance.

    I couldn't remember, so I looked in the API documentation for JTree. It wasn't long before I came to a method "addSelectionPath(TreePath)", which is what you want. I leave it as an exercise for you to figure out how to get a TreePath from your node.

  • 11gR1: expanding the current node in a tree programmatically

    Does anybody know how to programmatically expand the currently selected node in an af:tree in 11gR1? In all honesty I've searched a million OTN posts and tried a lot of examples but haven't got it working yet.
    At it's most simple I have a tree:
    <af:tree id="dirTree" value="#{bindings.NodesViewTree.treeModel}" var="node"
                 selectionListener="#{tbindings.NodesViewTree.treeModel.makeCurrent}" rowSelection="single"
                 binding="#{treeBean.dirTree}" >
      <f:facet name="nodeStamp">
          <af:outputText value="#{node.Name}" id="ot2"/>
      </f:facet>
    </af:tree>...of which the user can select a node, and the selectionListener updates the treeModel's current selected row.
    I want a button whose actionListener programatically takes the current selected row and expands (aka discloses it). I've a bean like follows:
    public class TreeBean {
      private RichTree dirTree;
      public void setDirTree(RichTree dirTree) { this.dirTree = dirTree; }
      public RichTree getDirTree() { return dirTree;  }
      public void doSomething(ActionEvent actionEvent) {
        RowKeySet selectedTreeNodes = dirTree.getSelectedRowKeys();
        RowKeySet disclosedTreeNodes = dirTree.getDisclosedTreeNodes();
       AdfFacesContext.getCurrentInstance().addPartialTarget(dirTree);
    }But I can't figure out what to do from here?
    Further to this say if we did manage to expand the current selected node, and I happened to know the oracle.jbo.Key of one of the expanded node's child nodes, how can I programatically select it.
    As mentioned I know a search of the forums yields a few hits for this topic, but none have yet solved my issue, so I'm hoping somebody can address my problem afresh please.
    Thanks for your assistance,
    CM.

    After a lot of playing it appears the JS approach is a dead-end. Ultimately what I'm attempting to achieve is to allow the user to right click a node in a tree, create a new node, and select the new node for the user. This can't be achieved in JS as the main work of creating the node must be done from the bindings/binding classes only accessible in a backing bean.
    So I've finally come up with a backing bean code solution where the user selects a node in a tree, and via a secondary action of selecting a context menu commandMenuItem the following code is executed. When I say "code solution", unfortunately I mean something that compiles & runs without throwing errors (hurrah!), but (sigh) doesn't work. I'm hoping somebody on the forum can give me a kick in the right direction please.
    The code:
      RichTree dirTree;
      public void anotherExperimentalCreate(ActionEvent actionEvent)  {
        String parentNodeType = getSelectedNodeType();
        if (parentNodeType.equals(DATABASE)) {
          // create user - todo
        } else if (parentNodeType.equals(FOLDER)) {
          // Fetch data from parent row required for new row
          oracle.jbo.domain.Number parentNodeId = getSelectedNodeId();
          oracle.jbo.domain.Number parentNodeTypeId = getSelectedNodeTypeId();
          DCIteratorBinding treeIterator = AdfUtils.findDCIteratorBinding(NODES_VIEW_TREE_ITERATOR);
          RowSetIterator treeRsi = treeIterator.getRowSetIterator();
          // Create new row
          // Why rsi.createAndInitRow? See - http://radio.weblogs.com/0118231/stories/2003/01/17/whyDoIGetTheInvalidownerexception.html
          Row newRow = treeRsi.createAndInitRow(new NameValuePairs(new String[]{"ParentNodeId"}, new Object[]{parentNodeId}));           
          oracle.jbo.domain.Number newNodeId = (oracle.jbo.domain.Number)newRow.getAttribute("NodeId");
          newRow.setAttribute("ParentNodeId", parentNodeId);
          newRow.setAttribute("NodeTypeId", parentNodeTypeId);
          newRow.setAttribute("Name", "New Folder" + newNodeId.toString());
          treeRsi.insertRow(newRow);
          // Commit changes and refresh iterator so it places new child row at correct location in tree
          FacesCtrlActionBinding commitBinding = AdfUtils.findFacesCtrlActionBinding("Commit");
          commitBinding.execute();     
          treeIterator.executeQuery();
          // Rebuild tree's current selected row by grabbing the current selected rows list (from which this action was invoked)
          // and add the additional new row to the end, with the goal of making the new row selected.
          // For "single" selection tree, and fact this routine can only be invoked via selecting a node, we only need
          // first element from iterator
          // Technique for casting to list derived from following OTN post:
          //    ADF Faces  - type of key element!
          List<Key> currentSelectedRowKeys = (List<Key>)dirTree.getSelectedRowKeys().iterator().next();
          ArrayList<Key> newSelectedRowKeys = new ArrayList<Key>();
          // Copy existing selected row keys to our new selected row key list
          for (Key currentSelectRowKey : currentSelectedRowKeys) {
            newSelectedRowKeys.add(currentSelectRowKey);
          // Add our new row's key to the end of the list
          newSelectedRowKeys.add(newRow.getKey());
          RowKeySetTreeImpl newSelectedRowKeySetTree = new RowKeySetTreeImpl();
          newSelectedRowKeySetTree.add(newSelectedRowKeys);
          // **** doesn't work ****
          dirTree.setSelectedRowKeys(newSelectedRowKeySetTree);
          AdfFacesContext.getCurrentInstance().addPartialTarget(dirTree);
      }As per the "doesn't work" annotation above, the problem is when the tree is refreshed via the PPR event, the tree hasn't selected the new row as passed to setSelectedRowKeys. Instead the state of the tree (expand/collapse) is the same as before the code is fired, though the new row is present as a child.
    Has anybody any clues at all on what I can attempt to try next please?
    Regards,
    CM.

Maybe you are looking for

  • Is it possible to skip the screen in BDC using IF statement.

    Hi Friends, I have written a report using BDC for tcode CO11 thru recording using CALL TRANSACTION. Case 1: If I go to transaction CO11 (screen number 100) and give the  order number which has more than 1 operations to be partially confirmed and pres

  • Blink while alarm on using shared variables with remote panel

    I am creating an application where I have front panel indicators data bound to shared variables.  I also set it up to have them blink when the alarm is on.  I am using the DSC module. This works great under the development environment.  But when I co

  • Best way to limit results from a query.

    I need to limit the number of results returned from the database to the first x rows. What I need is a database independant way to achieve this - i.e. I can't use LIMIT, TOP, etc. in my query. My question therefore is does statment.setMaxRows(x) rest

  • Automatic field updation in FI

    Hi, Accounting document gets genetraed automatically from many transaction of the other modules as a integration. I want to update the "Text field" of the accounting document based on some filed in original document field. I am updating the assignmen

  • Games for the Gamers

    How many people who frequent this forum and help out, or develop games for a living or otherwise, are actually gamers? i am for one. I was just wondering how many people who develop games have actually played a game before and know what the gamers wa