JTree hide Path

Hello,
I am using jTree to show folder named c:\Test, It has many directories & subdirectories. I would like to hide path & only name to be displayed.
C:\Test
c:\Test\folder1
c:\Test\folder2
c:\Test\Folder3.
c:\Test\Folder3\Folder31
I need display like this:
Test
Folder1
Folder2
Folder3
Folder31
How to do that??? Any Ideas.
Thanks

Note: This thread was originally posted in the [New To Java|http://forums.sun.com/forum.jspa?forumID=54] forum, but moved to this forum for closer topic alignment.

Similar Messages

  • JTree Hide Show nodes

    Hi All
    I have a JTree, and would like to hide some tree nodes based on a certain path, i have been using the setFilter and I can't seem to get to work.
    Regards
    M
    Code fragment below: using the FilterTreeModel
    void cmdShowSubset_actionPerformed(ActionEvent e) {
    DefaultMutableTreeNode tn = new DefaultMutableTreeNode(value);
    FilterTreeModel ftm = new FilterTreeModel(tn);
    ftm.setFilterNode(tn);
    Object[] oArray = new Object[1];
    oArray[0]="ABC communications";
    tp = new TreePath(oArray);
    subTree.setSelectionPath(tp);
    class FilterTreeModel
    extends javax.swing.tree.DefaultTreeModel {
    DefaultMutableTreeNode filterNode;
    public FilterTreeModel(DefaultMutableTreeNode root) {
    super(root);
    public int getChildCount(Object obj) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) obj;
    if (filterNode != null && !filterNode.isNodeDescendant(node)) {
    if (node.isNodeDescendant(filterNode))
    return 1;
    return 0;
    return super.getChildCount(node);
    public Object getChild(Object obj, int num) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) obj;
    if (filterNode != null && !filterNode.isNodeDescendant(node)) {
    if (node.isNodeDescendant(filterNode)) {
    TreeNode temp = filterNode;
    while (!node.isNodeChild(temp)) {
    temp = temp.getParent();
    return temp;
    return null;
    return super.getChild(node, num);
    public void setFilterNode(DefaultMutableTreeNode node) {
    filterNode = node;
    DefaultMutableTreeNode root = (DefaultMutableTreeNode)super.getRoot();
    super.fireTreeStructureChanged(root, super.getPathToRoot(root), null, null);

    When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read.

  • JTree - hidding root when showing the rest of the tree

    How can I hide only the root element when displaying the rest of a tree ?

    Hi Zauz,
    I unterstand your argumentation, but I have a problem with the implementation. Maybe you can show me your answer at a simple example:
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("world");
    DefaultMutableTreeNode country1 = new DefaultMutableTreeNode("france"); // Chield 1
    DefaultMutableTreeNode country2 = new DefaultMutableTreeNode("germany"); //Chield 2
    DefaultMutableTreeNode country3 = new DefaultMutableTreeNode("norway"); //Chield 3
    DefaultMutableTreeNode town1 = new DefaultMutableTreeNode("Frankfurt");
    DefaultMutableTreeNode town2 = new DefaultMutableTreeNode("Berlin");
    JTreetree = new JTree(root);
    root.add(country1);
    root.add(country2);
    root.add(country3);
    country2.add(town1);
    country2.add(town2);
    tree.expandRow(2); // 3 countries -1 = 2 children ????
    tree.setRootVisible(false); // result 0 tree invisible ???

  • Hide path info in the brower url

    Hi, all.
    I've search all over this forum but couldn't find a solution to my problem. I have a website hosted with JRun and IIS. What I want to do is that when users surf from page to page within my site, the url will always show only the domain name instead of domain:port_no/index.html.
    Now I can make the url remains the same by using frames but it's always shows the url of first page, something like this: http://www.mydomain.net:8100/mypath/index.html.
    What can I do to remove the port and path info from this url? i have no idea which i should change, the IIS settings or the JRun settings or even the JSP?
    Please help if you got any idea. Thanks a lot.

    Hi,
    I created one frame based test website with three frames. One top, left and the main frame.
    I tested with some sample pages and its working fine and i came to know that i missed to tell somthing.
    First i want to know the frameset's file name. If the frameset's filename is index.html then there is no problem. Other wise try to load the frameset instead of index.html as default file in the IIS website's properties.
    I have no problem with my frames. It will show only the www.domain.com in the address bar. I tested it with several subdirectories with sample html pages. it works fine and upto my last page it shows only the www.domain.com only.
    If the problem occurs again, give me the code of ur frame set.
    Sundar.

  • Confusion building JTree from path strings

    If I have a bunch of strings like this:
    "/dira/dir1/file1"
    "/dira/dir1/file2"
    "/dira/dir2/file1"
    "/dira/dir3/anotherdir/file1"
    etc.
    Does anybody have an easy solution to getting them in a JTree that looks like this:
       dira
        |
        +-dir1
        |  |
        |  +-file1
        |  |
        |  +-file2
        |
        +-dir2
        |  |
        |  +-file1
        |
        +-dir3
           |
           +-anotherdir
              |
              +-file1Mainly I am having trouble getting the tree to populate without duplicating nodes. For example dir1 gets listed twice. I am looking for a solution that will parse these strings and build the tree. I have found demos that read a file system, but nothing that works with strings. I have tried to pick apart the file system demos, but so far I can't get it to work correctly.
    Thanks,
    Jeff

    This compiles and works (with 1.4):
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    import java.util.HashMap;
    public class TreeStrings extends JFrame {
        public TreeStrings() {
            super("Tree strings");
            setDefaultCloseOperation(EXIT_ON_CLOSE);
            setSize(500, 400);
            String[] inputStrings = {"/dira/dir1/file1", "/dira/dir2/file1", "/dira/dir2/file2"}; // your bunch of Strings     
         DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("www");
         HashMap nodeMap = new HashMap();
         for(int i = 0; i < inputStrings.length; i++) {
             String s = inputStrings;
         DefaultMutableTreeNode lastNode = rootNode;
         int lastIndex = 0;
         while(true) {
              DefaultMutableTreeNode tempNode = null;
              int nextIndex = s.indexOf("/", lastIndex + 1); // <- i forgot + 1
              if(nextIndex != -1) { //we are somewhere in middle of s, checking nodes from root to leaf, one by one.
         String nodeKey = s.substring(0, nextIndex);
         if(nodeMap.get(nodeKey) == null) { //no such node, must make one
              String nodeName = s.substring(lastIndex, nextIndex); // you want the last nodeKey word for node name
         DefaultMutableTreeNode newNode = new DefaultMutableTreeNode(nodeName);
         nodeMap.put(nodeKey, newNode);
         lastNode.add(newNode);
         lastNode = newNode;
         else { //allready such node, just put it to be lastNode
         lastNode = (DefaultMutableTreeNode) nodeMap.get(nodeKey);
    lastIndex = nextIndex;
         else { //no more "/" , it means we are at end of s, and that all parent nodes for this leaf-node exist.
         // and we just add the leaf node to last node
         String leafName = s.substring(lastIndex, s.length());
         DefaultMutableTreeNode leafNode = new DefaultMutableTreeNode(leafName);
         lastNode.add(leafNode);
         break; // go to next s
         //You first make your tree structure with DefaultMutableNodes,
         //Then make a DefaultTreeModel with the root node,
         //Then make a Tree with the DefaultTreeModel
         DefaultTreeModel treeModel = new DefaultTreeModel(rootNode);
    JTree yourTree = new JTree(treeModel);
    getContentPane().add(yourTree, BorderLayout.CENTER);
    show();
    public static void main(String[] args) {
         new TreeStrings();
    Anything else?

  • Expand a path in JTree

    Hi all. Please help, I am trying to programmatically expand JTree with JTree.expandPath(path), but it only works one level downwards from the last physically selected node. Is this a bug, or am I doing something wrong?

    If you are using DefaultMutableTreeNode for your nodes, thenTreePath tp = new TreePath(theNode.getPath());gets you a path from the root to theNode. If you want that to be the selection, thentheTree.setSelectionPath(tp);and if you want it to be expanded and viewable thentheTree.expandPath(tp);If you aren't using DefaultMutableTreeNode, you will have to build the TreeNode[] that contains the nodes from the root down to theNode by some kind of loop; the rest of the code still works.

  • Problem with JPopupMenu and JTree

    Hi,
    Is there any way to have different JPopupMenu for every node.
    When I right click on the treenode there is popup menu have a "*JCheckBoxMenuItem*". By default the value of that checkbox is false. Now when i try to right click on a particular node and select the checkbox the selected value gets applied to rest of all nodes also.
    How can i just set the value of the checkbox to one perticular node.
    my code is
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress=new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
                    public void actionPerformed(ActionEvent ie) {
                            if(compress.getState()){
                                 compress.setState(true);
                                    System.out.println("compress clicked");
                            else{
                                 compress.setState(false);
                                    System.out.println("uncompress");
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if(path!=null && path==tree.getAnchorSelectionPath()) {
            super.show(c, x, y);
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() { createAndShowGUI(); }
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }Please help me as soon as possible.
    Thanks.
    Edited by: Kavita_S on Apr 23, 2009 11:49 PM

    Hi,
    Do you know this link?
    [How to Use Trees|http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html]
    Please help me as soon as possible.Sorry that I'm not good at English, I don't understand what you mean.
    Anyway, here's a quick example:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.tree.*;
    public class TreePopupMenuTest3 {
      public JComponent makeUI() {
        JTree tree = new JTree();
        tree.setComponentPopupMenu(new TreePopupMenu());
        JPanel p = new JPanel(new BorderLayout());
        p.add(new JScrollPane(tree));
        p.setPreferredSize(new Dimension(320, 240));
        return p;
      class TreePopupMenu extends JPopupMenu {
        private TreePath path;
        private JCheckBoxMenuItem compress = new JCheckBoxMenuItem("Compress");
        public TreePopupMenu() {
          super();
          add(compress);
          compress.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent ie) {
              if (compress.getState()) {
                System.out.println("compress clicked");
                setSelectedPath(path, true);
              } else {
                System.out.println("uncompress");
                setSelectedPath(path, false);
        public void show(Component c, int x, int y) {
          JTree tree = (JTree)c;
          path = tree.getPathForLocation(x, y);
          if (path!=null && path==tree.getAnchorSelectionPath()) {
            compress.setState(isSelectedPath(path));
            super.show(c, x, y);
      class MyData {
        public boolean flag;
        public String name;
        public MyData(String name, boolean flag) {
          this.name = name;
          this.flag = flag;
        @Override public String toString() {
          return name;
      //private Set<TreePath> selectedPath = new HashSet<TreePath>();
      private void setSelectedPath(TreePath p, boolean flag) {
        //if (flag) selectedPath.add(p);
        //else    selectedPath.remove(p);
        DefaultMutableTreeNode node =
              (DefaultMutableTreeNode)p.getLastPathComponent();
        Object o = node.getUserObject();
        if (o instanceof MyData) {
          ((MyData)o).flag = flag;
        } else {
          node.setUserObject(new MyData(o.toString(), flag));
      private boolean isSelectedPath(TreePath p) {
        //return selectedPath.contains(p);
        Object o =
              ((DefaultMutableTreeNode)p.getLastPathComponent()).getUserObject();
        return (o instanceof MyData)?((MyData)o).flag:false;
      public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
          public void run() {
            createAndShowGUI();
      public static void createAndShowGUI() {
        JFrame f = new JFrame();
        f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        f.getContentPane().add(new TreePopupMenuTest3().makeUI());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

  • How do you see the path in Yosemite?

    How do you see the path in Yosemite? What is the command to reveal the path to any given file? Is it somewhere in Finder?

    This is even better:
    Open the Terminal application
    Enter the line below exactly as it appears (Copy/Paste may/not work: highlight the line of text > switch to the Terminal app > cmd-v):
             defaults write com.apple.finder _FXShowPosixPathInTitle -bool TRUE
    *Note: there are single spaces after 'defaults', after 'write', after 'com.apple.finder', after '_FXShowPosixPathInTitle', and after '-bool'
    Then hit enter
    That's it! Go ahead and Quit Terminal (cmd-Q).
    Now:
    Close any Finder windows you have open.
    Open a new Finder window, and it should look like this:
    You can then get rid of the path bar at the bottom:
    Finder Menu > View > Hide Path bar -- or just use the keyboard-shortcut: cmd-opt-P

  • Path Layer Deselecting after Making Selection

    Hello,
         As I use this tool for multiple fast renderings, I love to use the Path Selection tool to modify the selection as such in quick succession. However, it seems as though after my slection is made, usign the path, the path layer disappears, needing reselection in the Path Window to do so. Here's what happens:
    Step 1
    I my paths, in which I want to first select this box, and then combine them at differing feather overlays. So naturally, I select the center most item, and...
    Step 2
    Up comes the dialog box as normal. I set the feather, hit enter and...
    Step 3
    Where did my other paths go?!?!
    Step 3 (Previous to CC, at least in CS5)
    Here I had the option to grab another path with my tool, overlap a feather at a different amount. Why does this happen?
    Is there a way to revert the tool back to the CS5 way of Selecting? Please let me know, thanks.

    I believe your paths are still there, if i look at the path's palette.
    When you deselect the path in the path's palette, no path will be visible in the stage. Try adding fill color and see.
    Step 01 and 02, your path was still selected in the path's palette but in step 03 it wasn't. Once you made the selection click on the path in the path's palette and see if it is visible or not.
    Check my tutorial on 'How to hide the path when adding layer style'. If the path is not selected in the path's palette, then it looks like it is not there.
    http://www.beekeepersblog.com/2012/12/ps-05-how-to-hide-path-when-adding.html

  • Reload JTree and keep expanded nodes

    Hi all,
    I have spent some time looking around on this, found some useful stuff, but I still cannot seem to get a result.
    Here is my situation:
    I have a JTree for a GUI desktop app. I build the tree from a database file. The user has the ability to refresh the tree to keep it in sync with any database changes. The problem is that when I refresh, all the nodes that were previously expanded are now collapsed again.
    Having looked around, I have seen a lot of JTree.expandRow() answers, but I don't want to use expandRow, as the rows will changes according to any db changes.
    I thought a good solution would be to trap any expand or collapse events and for each either add or remove the TreePath for the relevant node onto a List. When the users refreshes the tree, I thought I could run through the list and expand any TreeNodes I find. I also found someone advocating such an approach in another thread. BUT - it doesn't work for me Here is the code for my refresh. Any help/advice, greatly appreciated.
    Thanks in advance,
    Steve
    private void refreshBrowser(){
            System.out.println("Refresh browser - Started");       
            rootTreeNode.removeAllChildren(); // remove all nodes from root
            loadBrowserData(); // This method loads nodes from a database
             Iterator<TreePath> TPI = objectTreePaths.iterator(); // run throught my saved paths
            while (TPI.hasNext()) {
                TreePath yTreePath = TPI.next();           
                browserTree.expandPath(yTreePath); // Expand each found path
            treeModel.reload(); // model changed - reload it.
            System.out.println("Refresh browser - Complete");       
        }

    Here is my situation:
    I have a JTree for a GUI desktop app. I build the
    tree from a database file. The user has the ability
    to refresh the tree to keep it in sync with any
    database changes. The problem is that when I refresh,
    all the nodes that were previously expanded are now
    collapsed again.
    Having looked around, I have seen a lot of
    JTree.expandRow() answers, but I don't want to use
    expandRow, as the rows will changes according to any
    db changes.you could use:
    JTee.scrollPathToVisible(path);
    Where path is obtained in this way from a DefaultMutableTreeNode (TreeNode):
    TreePath path = new TreePath(((DefaultMutableTreeNode)node).getPath());
    I thought a good solution would be to trap any expand
    or collapse events and for each either add or remove
    the TreePath for the relevant node onto a List. When
    the users refreshes the tree, I thought I could run
    through the list and expand any TreeNodes I find. I
    also found someone advocating such an approach in
    another thread. BUT - it doesn't work for me When you perform a JTree.reload() call, it will collapse each node.
    My advice is to call JTree.reload() and then call JTree.scrollPathToVisible(path) for each TreeNode previously expanded.
    Hope this can help,
    regards

  • JTree leaf selection

    hi guys,
    I am developing a jTree for a networking product,which will show all the network elements present in the network.The tree also shows the device status like Up,Down etc.I have provided a button to refresh the jtree to update the status of the devices.But after updating the jtree when i try to expand or setSelected path to previously selected leaf,the jTree is expanding only till the parent of the leaf.Here is the code which i have written:
    public void addRootNodes()
              TreePath path=jTree.getSelectionPath();
              DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode)path.getLastPathComponent();
              TopologyUtilities.getNetworkCollectionDetails();
              TopologyUtilities.getRuntimeDataMapOnRefresh();
              initializeData();
              rootBusiness.removeAllChildren();
              rootNetwork.removeAllChildren();
              rootDiscovery.removeAllChildren();
              addRegionLocationToBusinessView();
              AddNodesToTree.addRoutersToNetworkView(configuredNetworkCollection, dataMap, rootNetwork);
              AddNodesToTree.addRoutersToDiscoveryView(discoveredNetworkCollection, configuredNetworkCollection, dataMap, rootDiscovery);
              treeModel.reload();
              panel.removeAll();
              jTree.setSelectionPath(path);
    Thanks for the help in advance
    bye,
    Srinivas

    Since you have a reference to a DefaultMutableTreeNode object, can't you do something like
    TreeNode[] nodes = n.getPath();
    TreePath path = new TreePath(nodes);
    tree.setSelectionPath(path);

  • Hid interface to Pelouse scale

    I've got a client who would like to read weigts from a Pelouze USB scale into LabVIEW.  The scale comes with a driver that is based on the HID interface.  There are several threads on the forums about talking to USB devices using USB RAW through VISA and on talking to HID devices, but I couldn't find any thread that claimed that the HID idea had been done successfully from LabVIEW.
    Although it appears that one can disassociate the device from the HID driver and access it through USB RAW, we have decided not to go that route.  (There are too many steps required to set up the scale in this manner.  It wouldn't be appropriate for the eventual customer.)  So calling HID.dll seems to be the only option.  However, my reading of the threads seems to indicate that this is pretty complicated.  Even if we understood the hid.dll interface, we still don't have any specs on how the scale uses the hid interface.
    Has anyone succeeded in talking to a Pelouze scale from LabVIEW?  Or any of the other numerous USB scales that use an HID interface?
    Thanks,
       DaveT
    David Thomson Original Code Consulting
    www.originalcode.com
    National Instruments Alliance Program Member
    Certified LabVIEW Architect
    There are 10 kinds of people: those who understand binary, and those who don't.

    Dave Thomson wrote:
    I've got a client who would like to read weigts from a Pelouze USB scale into LabVIEW.  The scale comes with a driver that is based on the HID interface.  There are several threads on the forums about talking to USB devices using USB RAW through VISA and on talking to HID devices, but I couldn't find any thread that claimed that the HID idea had been done successfully from LabVIEW.
    Although it appears that one can disassociate the device from the HID driver and access it through USB RAW, we have decided not to go that route.  (There are too many steps required to set up the scale in this manner.  It wouldn't be appropriate for the eventual customer.)  So calling HID.dll seems to be the only option.  However, my reading of the threads seems to indicate that this is pretty complicated.  Even if we understood the hid.dll interface, we still don't have any specs on how the scale uses the hid interface.
    Has anyone succeeded in talking to a Pelouze scale from LabVIEW?  Or any of the other numerous USB scales that use an HID interface?
    Thanks,
       DaveT
    What do you mean when you say the scale comes with a driver that is based on the HID interface. Is that a DLL? Why would you then want to access HID.DLL instead of this specific driver DLL?
    HID.DLL is the generic HID Windows API to all HID devices (that are not captured by the Windows kernel for user events, such as the mice and keyboards). So your scale implements a HID USB class and Windows recognizes that and makes it available as such through HID.DLL. However accessing a HID device through HID.DLL is still pretty low level as you simply get a data stream and need to decode and encode the device specific information from and to that stream. Not to speak of the various hoops you have to jump through to localize and open the device through setupAPI.dll and HID.dll, before you can talk to it. Another problem is that the data stream protocol of proprietary HID devices is seldom documented.
    So if your scale comes with a DLL driver to access it, go with that driver. Of course you will need some documentation of the API of that driver and then using the Call Library Node to call into it. Going the direct HID path is really not a good solution unless you know the HID data stream protocol of the device AND you have no other way to do it (for instance if you need to interface to your own HID device design).
    Rolf Kalbermatter
    Message Edited by rolfk on 08-25-2009 08:48 AM
    Rolf Kalbermatter
    CIT Engineering Netherlands
    a division of Test & Measurement Solutions

  • JTree.getNextMatch() only works on visible nodes?  Any alternatives?

    I'm trying to search for and select a node in the tree based on user input. I was trying to use JTree.getNextMatch(), but that method returns a NULL TreePath if the node being searched for is not currently visible (if this is, indeed, the case, why isn't this noted in the API documentation???)
    Anyway, is there a method that returns the path of a node, whether visible or not? I could then use that info to make the path visible using JTree.scrollPathToVisible(path).
    I found a link at
    http://www.exampledepot.com/egs/javax.swing.tree/FindNode.html
    that describes various methods, including getNextMatch() - and from the comments in that code, I got the notion that this is only for visible nodes. But I was hoping that since 2003, there have been additional methods in the standard toolkit which I can use rather than manually descend the tree myself.

    If you're using DefaultMutableTreeNodes, you can use the depthFirstEnumeration method, API is here: http://java.sun.com/j2se/1.5.0/docs/api/javax/swing/tree/DefaultMutableTreeNode.html#depthFirstEnumeration()

  • JTree odd click behavior w/ L&F

    I have a JTree that works perfectly until I change the L&F. In the mouse down event, once the line of code executes:
    UIManager.setLookAndFeel("string");
    SwingUtilities.updateComponentTreeUI(root);
    (root is the entire JFrame where the tree and the other components lie)
    Before this is executed, the tree "leaves" require one click to run my code -- basically updating a JLabel with the current path. This is trapped on the mouse down event.
    Afterwards, however, the tree needs 2 clicks before it'll register the current node.
    Do I have to update something in the JTree when the L&F are changed?
    Thanks --
    Steve

    Seems like the JTree selection path is the only thing not updating correctly...
    This code:
    tree.getSelectionPath()
    seems to be returning the path right before it -- unless you double click.
    Is this a Swing bug?

  • Custom TreeCellRenderer not working in Program

    The following 2 lines set my TreeCellRenderer
    FSDirectoryCellRenderer renderer1 = new FSDirectoryCellRenderer();
    jtree.setCellRenderer(renderer1);
    Rendering is not working in the Below Program. But If I comment the above 2 lines the default rendering is working. There is a probelm with my rendering class FSDirectoryCellRenderer which I am not able to figure out. PLease help me out
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTree;
    import javax.swing.UIManager;
    import javax.swing.border.BevelBorder;
    import javax.swing.border.SoftBevelBorder;
    import javax.swing.event.TreeSelectionEvent;
    import javax.swing.event.TreeSelectionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreeCellRenderer;
    import javax.swing.tree.TreePath;
    public class UniversityLayout extends JFrame {
         private JTree jtree = null;
         private DefaultTreeModel defaultTreeModel = null;
         private JTextField jtfStatus;
         public UniversityLayout() {
              super("A University JTree Example");
              setSize(300, 300);
              Object[] nodes = buildJTree();
              DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
              renderer.setOpenIcon(new ImageIcon("opened.gif"));
              renderer.setClosedIcon(new ImageIcon("closed.gif"));
              renderer.setLeafIcon(new ImageIcon("leaf.gif"));
              jtree.setCellRenderer(renderer);
              jtree.setShowsRootHandles(true);
              jtree.setEditable(false);
              jtree.addTreeSelectionListener(new UTreeSelectionListener());
              FSDirectoryCellRenderer renderer1 = new FSDirectoryCellRenderer();
              jtree.setCellRenderer(renderer1);
              JScrollPane s = new JScrollPane();
              s.getViewport().add(jtree);
              getContentPane().add(s, BorderLayout.CENTER);
              jtfStatus = new JTextField(); // Use JTextField to allow copy operation
              jtfStatus.setEditable(false);
              jtfStatus.setBorder(new SoftBevelBorder(BevelBorder.LOWERED));
              getContentPane().add(jtfStatus, BorderLayout.SOUTH);
              TreePath path = new TreePath(nodes);
              jtree.setSelectionPath(path);
    //          jtree.scrollPathToVisible(path);
         class FSDirectoryCellRenderer extends JLabel implements TreeCellRenderer {
              private Color textSelectionColor;
              private Color textNoSelectionColor;
              private Color backgroundSelectionColor;
              private Color backgroundNoSelectionColor;
              private boolean sel;
              public FSDirectoryCellRenderer() {
                   super();
                   textSelectionColor = UIManager.getColor("Tree.selectionForeground");
                   textNoSelectionColor = UIManager.getColor("Tree.textForeground");
                   backgroundSelectionColor = UIManager
                             .getColor("Tree.selectionBackground");
                   backgroundNoSelectionColor = UIManager
                             .getColor("Tree.textBackground");
                   setOpaque(false);
              public Component getTreeCellRendererComponent(JTree tree, Object value,
                        boolean selected, boolean expanded, boolean leaf, int row,
                        boolean hasFocus) {
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                   Object obj = node.getUserObject();
                   setText(obj.toString());
                   if (obj instanceof Boolean) {
                        setText("Loading");
                   if (obj instanceof NodeIconData) {
                        NodeIconData nodeIconData = (NodeIconData) obj;
                        if (expanded) {
                             setIcon(nodeIconData.getExpandedIcon());
                        } else {
                             setIcon(nodeIconData.getNormalIcon());
                   } else {
                        setIcon(null);
                   setFont(jtree.getFont());
                   setForeground(selected ? textSelectionColor : textNoSelectionColor);
                   setBackground(selected ? backgroundSelectionColor
                             : backgroundNoSelectionColor);
                   sel = selected;
                   return this;
         private Object[] buildJTree() {
              Object[] nodes = new Object[4];
              DefaultMutableTreeNode root = new DefaultMutableTreeNode(new College(1, "College"));
              DefaultMutableTreeNode parent = root;
              nodes[0] = root;
              DefaultMutableTreeNode node = new DefaultMutableTreeNode(new College(2, "Class 1"));
              parent.add(node);
              parent = node;
              parent.add(new DefaultMutableTreeNode(new College(3, "Section A")));
              parent.add(new DefaultMutableTreeNode(new College(4, "Section B")));
              parent = root;
              node = new DefaultMutableTreeNode(new College(5, "Class 2"));
              parent.add(node);
              nodes[1] = node;
              parent = node;
              node = new DefaultMutableTreeNode(new College(6, "Science"));
              parent.add(node);
    //          nodes[2] = node;
              parent = node;
              parent.add(new DefaultMutableTreeNode(new College(7, "Computer Science")));
              parent.add(new DefaultMutableTreeNode(new College(8, "Information Science")));
              parent = (DefaultMutableTreeNode)nodes[1];
              node = new DefaultMutableTreeNode(new College(9, "Arts"));
              parent.add(node);
              nodes[2] = node;
              parent = (DefaultMutableTreeNode)nodes[2];
              parent.add(new DefaultMutableTreeNode(new College(10, "Drawing")));
              node = new DefaultMutableTreeNode(new College(11, "Painting"));
              parent.add(node);
              nodes[3] = node;
              parent = (DefaultMutableTreeNode)nodes[1];
              parent.add(new DefaultMutableTreeNode(new College(12, "Telecom")));
              defaultTreeModel = new DefaultTreeModel(root);
              jtree = new JTree(defaultTreeModel);
              return nodes;
         public static void main(String argv[]) {
              UniversityLayout frame = new UniversityLayout();
              frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              frame.setVisible(true);
         class UTreeSelectionListener implements TreeSelectionListener {
              public void valueChanged(TreeSelectionEvent e) {
                   TreePath path = e.getPath();
                   Object[] nodes = path.getPath();
                   String status = "";
                   for (int k = 0; k < nodes.length; k++) {
                        DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodes[k];
                        College nd = (College) node.getUserObject();
                        status += "." + nd.getId();
                   jtfStatus.setText(status);
    class College {
         protected int id;
         protected String name;
         public College(int id, String name) {
              this.id = id;
              this.name = name;
         public int getId() {
              return id;
         public String getName() {
              return name;
         public String toString() {
              return name;
    }

    It works fine for me (after commenting out the part about NodeIconData, whose source you didn't provide). What is the behavior you expect to see but don't? Is it that when you click on a tree node, it doesn't appear "selected?"
    Why not extends DefaultTreeCellRenderer? You appear to be doing minimal configuring (sometimes changing the text and/or icon of the node).
         class FSDirectoryCellRenderer extends DefaultTreeCellRenderer {
              public FSDirectoryCellRenderer() {
                   super();
                   setOpaque(false);
              public Component getTreeCellRendererComponent(JTree tree, Object value,
                        boolean selected, boolean expanded, boolean leaf, int row,
                        boolean hasFocus) {
                   super.getTreeCellRendererComponent(tree, value, selected, expanded,
                                       leaf, row, hasFocus);
                   DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
                   Object obj = node.getUserObject();
                   setText(obj.toString());
                   if (obj instanceof Boolean) {
                        setText("Loading");
    //               if (obj instanceof NodeIconData) {
    //                    NodeIconData nodeIconData = (NodeIconData) obj;
    //                    if (expanded) {
    //                         setIcon(nodeIconData.getExpandedIcon());
    //                    } else {
    //                         setIcon(nodeIconData.getNormalIcon());
    //               } else {
                        setIcon(null);
                   return this;
         }

Maybe you are looking for

  • HT201269 how can i restore my iPad?

    how can i restore my iPad?

  • Oracle Application Server

    1) I understand that Oracle Application Server (OAS) is no longer supported by Oracle. Oracle 9i Application Server (9iAS) has replaced OAS. Is this correct info? 2) We have Oracle Application (ERP) running on database 8.1.7 in 1 unix box. We are cre

  • Saving copies of email as PDF or Pages/Word documents

    I have to save certain emails that I receive and keep them as a permanent record, as a PDF, Word etc...file. It needs to be something that others can view with a PC. I have been using Google to download my emails as a PDF, then save them to my PC but

  • Currecy conversion not working for an entity in HFM

    We have an entity in HFM under UK. For some reason the currency conversion is not working at parent level for that entity. It is showing right currency at GBP level butwhen we open at USD level it is not converting.   iverified the properties. theylo

  • Issues when Downloading Large Datasets to Excel and CSV

    Hi, Hoping someone could lend a hand on the issues described below. I have a prompted dahsboard that, dependent upon prompts selected, can return detail datasets. THe intent of this dashboard is to AVOID giving end users Answers Access, but still pro