JTree lineStyle in XP

No lines appear between the nodes when testing in XP with windows LAF. I've tried setting
tree.putClientProperty("JTree.lineStyle", "Angled") ;
but it has not effect. Any ideas?
-d

This is a known bug, and you'll need to apply the fix
posed at this link.
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=488
7931Thanks for the info!

Similar Messages

  • PutClientProperty("JTree.lineStyle", "Angled") in JDK 1.4.2

    In 1.4.2 the look of the tree has been updated to remove the ---- line handles on the tree by default. I would like to continue displaying those as they appeared in earlier versions without using the older classic windows look and feel for the rest of the application (so I don't want to use the command line toggle that alters this).
    Has anyone gotten the above client property to work properly on the tree in 1.4.2? I've been having difficulties with this. I generally do something like the following:
    tree.putClientProperty("JTree.lineStyle", "Angled");
    tree.repaint();
    OR
    tree.updateUI();
    Would it also be possible to override this for all instances of JTree's in the application by setting something in the UIManager?

    There seems to be a great deal of confusion here.
    The property "JTree.lineStyle" is (unfortunately) only used by
    MetalTreeUI, and won't have any effect in the Windows L&F. It is a
    client property, which (unfortunately) is a different mechanism from
    the UIManager defaults.
    The bug is in WindowsTreeUI and will be fixed in 1.5. There is no
    easy workaround, except to replace the UI class with a fixed one. Here
    is an attempt which seems to work. I don't give any guarantees, but
    please let me know how it works for you.
    import com.sun.java.swing.plaf.windows.WindowsTreeUI;
    import java.awt.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.plaf.basic.*;
    import javax.swing.plaf.*;
    import javax.swing.tree.*;
    * A subclass of JTree that fixes bug 4887931: Tree lines
    * missing on Windows XP
    public class JTree14 extends JTree {
        public JTree14() {
        public JTree14(Object[] value) {
         super(value);
        public JTree14(Vector value) {
         super(value);
        public JTree14(Hashtable value) {
         super(value);
        public JTree14(TreeNode root) {
         super(root);
        public JTree14(TreeNode root, boolean asksAllowsChildren) {
         super(root, asksAllowsChildren);
        public JTree14(TreeModel newModel) {
         super(newModel);
        public void setUI(TreeUI ui) {
         if (ui instanceof WindowsTreeUI &&
             System.getProperty("java.version").equals("1.4.2")) {
             ui = new FixedWindowsTreeUI();
         super.setUI(ui);
        private static class FixedWindowsTreeUI extends BasicTreeUI {
         protected void ensureRowsAreVisible(int beginRow, int endRow) {
             if(tree != null && beginRow >= 0 && endRow < getRowCount(tree)) {
              Rectangle visRect = tree.getVisibleRect();
              if(beginRow == endRow) {
                  Rectangle     scrollBounds = getPathBounds(tree, getPathForRow
                                              (tree, beginRow));
                  if(scrollBounds != null) {
                   scrollBounds.x = visRect.x;
                   scrollBounds.width = visRect.width;
                   tree.scrollRectToVisible(scrollBounds);
              else {
                  Rectangle   beginRect = getPathBounds(tree, getPathForRow
                                         (tree, beginRow));
                  Rectangle   testRect = beginRect;
                  int         beginY = beginRect.y;
                  int         maxY = beginY + visRect.height;
                  for(int counter = beginRow + 1; counter <= endRow; counter++) {
                   testRect = getPathBounds(tree,
                                   getPathForRow(tree, counter));
                   if((testRect.y + testRect.height) > maxY)
                       counter = endRow;
                  tree.scrollRectToVisible(new Rectangle(visRect.x, beginY, 1,
                                        testRect.y + testRect.height-
                                        beginY));
         protected TreeCellRenderer createDefaultCellRenderer() {
             return new WindowsTreeUI().new WindowsTreeCellRenderer();
    }Cheers,
    Leif Samuelsson
    Java Swing Team
    Sun Microsystems, Inc.

  • JTree.linestyle doesn't show with Windows Look&Feel

    Hi guys,
    I've a problem with the JTree.linestyle. In my application works fine with the GTK and the Metal L&F, but in the Windows L&F doesn't shows any lines or angles.
    I'm using j2sdk1.4.2.
    Anyone else have the same problem? Any solution?
    Thank you very much in advance.
    Best Regards,
    Carlos.

    Solved in http://forum.java.sun.com/thread.jsp?forum=57&thread=433899&start=0&range=15#1951313

  • JTree.lineStyle : alignment of lines

    Hi folks,
    I'm trying to align the angled node line to the top of the child node.
    tree.putClientProperty("JTree.lineStyle", "Angled")  draws lines showing the relationship between nodes on the tree. However the line is joined to the child node aligned vertically to the child's centre. My child node can be multline, e.g. a multline description, and I'd like the join line to connect to the child node at the top where the node's icon is and where the text begins.
    I'm sure this must be possible but I can't work it out.
    Thanks,
    Des

    Okay, here's one, but you'll do much better if you ask on Swing: it probably has 20x the readership of Java 2D.
    import java.awt.*;
    import javax.swing.*;
    public class X {
        public static void main(String[] args)  {
            UIManager.put("Tree.hash", Color.RED);
            JTree tree = new JTree();
            JFrame f = new JFrame("X");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(tree);
            f.setSize(400, 300);
            f.setLocationRelativeTo(null);
            f.setVisible(true);

  • JTree - Color setting of linestyle

    Between the root and the node elements there are lines to show the connection between the element/levels. How can I change the color of these lines and/or how can I hide these lines?

    Example:
    private JTree tree;
    tree.putClientProperty("JTree.lineStyle", "None");

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

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

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

  • JTree: how not to render the "tree connecting lines"

    I have a JTree.
    I would like that my custom tree renderer (using windows LAF) did not paint the dotted line that connect the hierarchy nodes. setting the icon to null in the default renderer only do not paint the folder. How can I disable also the painting of the dotted line?
    using
    tree.putClientProperty("JTree.lineStyle", "None")
    I disable it for the whole tree.
    First of all this do not work on Windows LAF. Then I'd like to disable only on certain branches or nodes, that are somehow as "empty containers", while keeping hte default feature for the "good branches".
    any idea?
    thanks
    Edited by: Davide_Gesino on Nov 8, 2009 5:24 AM

    hii,
    one from possible:
    tree.putClientProperty("JTree.lineStyle", "Horizontal"); a lots examples (runnable) at http://www.java2s.com/Code/Java/Swing-JFC/Tree.htm
    ... kopik

  • JTree Nimbus selection treeNode

    I made a jtree with a custom TreeCellRenderer. The leaf nodes are a jpanel with a checkbox in and JPanel. The problem now is that when you select a tree node, there is a selection color box beside the jpanel.
    Here is a sscce:
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Component;
    import java.awt.Dimension;
    import javax.swing.JCheckBox;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JPanel;
    import javax.swing.JTree;
    import javax.swing.UIManager;
    import javax.swing.UIManager.LookAndFeelInfo;
    import javax.swing.UnsupportedLookAndFeelException;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeCellRenderer;
    public class Users {
        private static JFrame frame;
        private static JPanel usersPanel;
        private JTree usersTree;
        public Users(){
            usersPanel = new JPanel();
            DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Gebruikers");
            DefaultMutableTreeNode willie = new DefaultMutableTreeNode("Willie");
            DefaultMutableTreeNode Anna = new DefaultMutableTreeNode("Anna");
            rootNode.add(willie);
            rootNode.add(Anna);
            usersTree = new JTree(rootNode);
            myTreeWithCheckBoxRenderer renderer = new myTreeWithCheckBoxRenderer();
            usersTree.setCellRenderer(renderer);
            usersTree.setRootVisible(true);
            usersTree.setEditable(false);
            usersTree.setOpaque(false);
            usersPanel.add(usersTree);
        class myTreeWithCheckBoxRenderer extends DefaultTreeCellRenderer {
            DefaultTreeCellRenderer renderer = new DefaultTreeCellRenderer();
            JPanel panel;
            JCheckBox checkBox;
            JLabel label;
            public myTreeWithCheckBoxRenderer() {
                checkBox = new JCheckBox();
                label = new JLabel("Gebruikers");
                panel = new JPanel(new BorderLayout());
                panel.add(checkBox, BorderLayout.WEST);
                panel.add(label, BorderLayout.EAST);
                panel.setBackground(Color.red);
            @Override
            public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
                Component returnValue;
                if(!leaf){
                    renderer.setBackgroundSelectionColor(null);
                    renderer.setText("Gebruikers");
                    returnValue = renderer;
                else{
                    if(hasFocus){
                        panel.setBackground(Color.blue);
                    returnValue = panel;
                return returnValue;
        private static void createAndShowGUI(){
            new Users();
            frame = new JFrame("Tree");
            frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            frame.setContentPane(usersPanel);
            frame.pack();
            frame.setPreferredSize(new Dimension(800, 600));
            frame.setLocationRelativeTo(null);
            frame.setVisible(true);
         public static void main (String[] args){
            try {
                for (LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        UIManager.setLookAndFeel(info.getClassName());
                        break;
            } catch (UnsupportedLookAndFeelException e) {
                // handle exception
            } catch (ClassNotFoundException e) {
                // handle exception
            } catch (InstantiationException e) {
                // handle exception
            } catch (IllegalAccessException e) {
                // handle exception
            javax.swing.SwingUtilities.invokeLater(new Runnable(){
                @Override
                public void run(){
                    createAndShowGUI();
    }I tried using a DefaultTreeCellRenderer and use the setBackgroundSelectionColor() method to null, but it doesn't change anything. Also setting the background of the JPanel to null doesn't make a change when you check with (if(hasFocus)). However I have the impression that nimbus is causing the problem, because if you comment the nimbus part out, you don't have the selection box anymore.
    Does anyone has an idea to solve this?
    Edited by: Kligham on 30-aug-2010 19:25

    Kligham wrote:
    Thank you very much!You're welcome.
    Kligham wrote:
    Problem solved. So since this cell background rendering is a Nimbus "feature", can I assume that the "not displaying of angled lines" also is a Nimbus "feature". Since the JTree tutorial says this should do the trick:
    usersTree.putClientProperty("JTree.lineStyle", "Angled");So I probably have to override it the same way, so I was wondering how you know what UIDefaults there are?Well, "JTree.lineStyle" is actually a client property and not a UIDefaults property. In other words, "JTree.lineStyle" is on the same logical level as "Nimbus.Overrides". Unfortunately, there is no way to determine which client properties a component or a component UI implementation supports except carefully examining its source code. javax.swing.plaf.synth.SynthTreeUI (the Nimbus TreeUI implementation) doesn't seem to support any client properties. It might be handled somewhere else, though.
    As an alternative to using "JTree.lineStyle", you could try to use a backgroundPainter that draws angle lines instead of the "do nothing" painter I suggested.
    To determine which UIDefaults properties are available for a given LaF implementation, you can iterate over the UIDefaults' entrySet (UIDefaults is a subclass of Hashtable). For Nimbus specifically, Jasper Potts already did that. See the [corresponding blog entry|http://www.jasperpotts.com/blog/2008/08/nimbus-uimanager-uidefaults/] and [Nimbus UIDefaults Properties List|http://jasperpotts.com/blogfiles/nimbusdefaults/nimbus.html]

  • JTrees, JDK 1.4.2 and Windows XP

    Hi,
    I noticed that under JDK 1.4.2 with Windows XP, JTrees are drawn without the lines connecing the children the parent node. I want to draw the lines. Can anyone tell me how?
    thanks

    Let me explain a little clearer...
    I am using the System look & feel. I am running on windows xp and the java version is 1.4.2. The problem is that that in the system look and feel of swing under XP, the JTrees are drawn w/o lines connecting the parent folder to the subfolder. I think it's unesthetic and I would like to know if I can "bring back" these lines.
    In the java look and feel it is possible with this method:
    tree.putClientProperty("JTree.lineStyle", "Angled");
    However this only works for the java look and feel. Is there something similar to the this code that works for system look & feel????

  • How do I get a dotted line to connect nodes in a JTree?

    I am trying to recreate a Windows Explorer application, does anyone know how they get the dotted lines to connect the nodes in the JTree????

    JTree uses a specific line style to represent the edges between nodes. The default is no edges, but we can set JTree�s lineStyle client property so that each parent node appears connected to each of its child nodes by an angled line:
    myJTree.putClientProperty("JTree.lineStyle", "Angled");
    We can also set this property such that each tree cell is separated by a horizontal line:
    myJTree.putClientProperty("JTree.lineStyle", "Horizontal");
    To disable the line style:
    myJTree.putClientProperty("JTree.lineStyle", "None");
    As with any Swing component, we can also change the UI resource defaults used for all instances of the JTree class. For instance, to change the color of the lines used for rendering the edges between nodes as described above, we can modify the entry in the UI defaults table for this resource as follows:
    UIManager.put("Tree.hash", new ColorUIResource(Color.lightGray))
    Hope this serves your purpose.
    Regards,
    Sachin Shanbhag

  • Text in Customize JTree has a different background

    Hi,
    I created a customized JTree with a background color of 128, 128, 192 for the panel and the JTree. But when I run the application, I get the text with a white blocked background. How can I make the background of the text look like that of the JTree.
    tree.setBackground(new Color(128,128,192));
    tree.setForeground(new Color(128,128,192));
    Anthony
    package com.reports;
    import javax.swing.*;
    import javax.swing.plaf.*;
    import javax.swing.event.HyperlinkEvent;
    import javax.swing.tree.*;
    import java.util.TreeMap;
    import java.util.*;
    import java.awt.*;
    public class PanelNavigation extends JPanel {
    private JTree tree;
    private DefaultTreeModel treeModel;
    public PanelNavigation() {
    super();
    setUIManager();
    setBackground(new Color(128,128,192)); // Set the Background color
    setPreferredSize( new Dimension(170, 130));
              String [] master = {"Monthly Report"};
    String [] desk = {"Long Term Funding",
                   "Bullet Swaps",
    "Volatility",
    "Short Term Notes"};
    String [] scenarios = {"Dealer List", "Weighting Preference"};
    Hashtable scenariosLevel = new Hashtable();
    scenariosLevel.put("Change Global Settings", scenarios);
              Hashtable dlrPref = new Hashtable();
    dlrPref.put("Master View", master);
    dlrPref.put("Details By Desk", desk);
    dlrPref.put("Scenarios", scenariosLevel);
    tree = new JTree(dlrPref);
    tree.putClientProperty("JTree.lineStyle", "Angled");
    tree.setBackground(new Color(128,128,192));
    tree.setForeground(new Color(128,128,192));
    tree.setVisible(true);
    add(tree);
    public PanelNavigation(Object [] parentNode, Object [] leafNode) {
    super();
    setUIManager();
    setBackground(new Color(128,128,192));
    // setForeground(Color.white);
    public void setUIManager() {
    UIManager.put("Tree.leafIcon", new ImageIcon("reportLeaf.gif"));
    UIManager.put("Tree.openIcon", new ImageIcon("parentLeaf.gif"));

    I think you'll have to use a DefaultTreeCellRenderer.
    Create a new class that extends DefaultTreeCellRenderer.
    <code>
    import javax.swing.tree.DefaultTreeCellRendere;
    public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus)
    super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
    setBackgroundColor(new Color(128,128,192));
    </code>
    You can also use SetBackgroundSelectionColor() and SetBackgroundNonSelectionColor()
    Hope this helps you :D

  • A bug in the JTree(Missing some nodes)

    I have an application which implement a JTree & DnDTree. The left hand side is the original JTee, the right hand size is DnDTree which allows user to Drag and Drop some node from left JTree. The bug is: when I grag some node to right DnDTree, once I then click the left JTree, some nodes will be missing. I try my best for more than one week, but still couldn't fix it, could anybody take time to fina a way to fix it? The piece of code of creating JTree is as follow:
    /*public void createTestTree()
    DefaultMutableTreeNode rootRight = new DefaultMutableTreeNode("Root");
    DefaultMutableTreeNode root = createTreeModel();
    treeLeft = new DnDTree(root, true); //JTree(root, true);
    treeLeft.putClientProperty("JTree.lineStyle", "Angled");
    treeLeft.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    treeLeft.addTreeExpansionListener(new TreeExpansionListener(){
    public void treeCollapsed(TreeExpansionEvent e) {
    public void treeExpanded(TreeExpansionEvent e) {
    UpdateStatus updateThread;
    TreePath path = e.getPath();
    FileNode node = (FileNode)
    path.getLastPathComponent();
    if( ! node.isExplored()) {
    DefaultTreeModel model = (DefaultTreeModel)treeLeft.getModel();
    UpdateStatus us = new UpdateStatus();
    us.start();
    node.explore();
    model.nodeStructureChanged(node);
    class UpdateStatus extends Thread {
    public void run() {
    try { Thread.currentThread().sleep(450); }
    catch(InterruptedException e) { }
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    treeRight = new DnDTree(rootRight, true); treeRight.putClientProperty("JTree.lineStyle", "Angled");
    treeRight.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
    treeRight.addTreeExpansionListener(new TreeExpansionListener(){
    public void treeCollapsed(TreeExpansionEvent e) {
    public void treeExpanded(TreeExpansionEvent e) {
    UpdateStatus updateThread;
    TreePath path = e.getPath();
    FileNode node = (FileNode)
                             path.getLastPathComponent();               
    if( ! node.isExplored()) {
    DefaultTreeModel model = (DefaultTreeModel)treeRight.getModel();
    UpdateStatus us = new UpdateStatus();
    us.start();
    node.explore();
    model.nodeStructureChanged(node);
    class UpdateStatus extends Thread {
    public void run() {
    try { Thread.currentThread().sleep(450); }
    catch(InterruptedException e) { }
    SwingUtilities.invokeLater(new Runnable() {
    public void run() {
    My FileNode class is:
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.tree.*;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.File;
    import java.util.EventObject;
    public class GoodFileTree extends JPanel {
         public GoodFileTree() {
              final JTree tree = new JTree(createTreeModel());
              JScrollPane scrollPane = new JScrollPane(tree);
              this.add(scrollPane, BorderLayout.WEST);
              //getContentPane().add(scrollPane, BorderLayout.CENTER);
              this.add(GJApp.getStatusArea(),BorderLayout.SOUTH);
              //getContentPane().add(GJApp.getStatusArea(),BorderLayout.SOUTH);
              tree.addTreeExpansionListener(new TreeExpansionListener(){
                   public void treeCollapsed(TreeExpansionEvent e) {
                   public void treeExpanded(TreeExpansionEvent e) {
                        UpdateStatus updateThread;
                        TreePath path = e.getPath();
                        FileNode node = (FileNode)
                                            path.getLastPathComponent();
                        if( ! node.isExplored()) {
                             DefaultTreeModel model = (DefaultTreeModel)tree.getModel();
                             GJApp.updateStatus("exploring ...");
                             UpdateStatus us = new UpdateStatus();
                             us.start();
                             node.explore();
                             model.nodeStructureChanged(node);
                   class UpdateStatus extends Thread {
                        public void run() {
                             try { Thread.currentThread().sleep(450); }
                             catch(InterruptedException e) { }
                             SwingUtilities.invokeLater(new Runnable() {
                                  public void run() {
                                       GJApp.updateStatus(" ");
         private DefaultMutableTreeNode createTreeModel() {
              /*File root = new File("E:/");
              FileNode rootNode = new FileNode(root);
              rootNode.explore();
              return new DefaultTreeModel(rootNode);*/
              DefaultMutableTreeNode top = new DefaultMutableTreeNode("Root");
              File[] fArr = File.listRoots();
              File fDrive;
              FileNode driveNode;
              for(int i=0; i<fArr.length; ++i)
                   fDrive = fArr;
                   driveNode = new FileNode(fDrive);
                   top.add(driveNode);
              return top;
         /*public static void main(String args[])
              try
                   UIManager.setLookAndFeel(
                   UIManager.getSystemLookAndFeelClassName()
                   //UIManager.getCrossPlatformLookAndFeelClassName()
              catch (Exception e)
              GJApp.launch(new GoodFileTree(),"JTree File Explorer",
                                            300,300,450,400);
    class FileNode extends DefaultMutableTreeNode {
         private boolean explored = false;
         public FileNode(File file)      {
              setUserObject(file);
         public boolean getAllowsChildren() { return isDirectory(); }
         public boolean isLeaf()      { return !isDirectory(); }
         public File getFile()          { return (File)getUserObject(); }
         public boolean isExplored() { return explored; }
         public boolean isDirectory() {
              File file = getFile();
              return file.isDirectory();
         public String toString() {
              File file = (File)getUserObject();
              String filename = file.toString();
              int index = filename.lastIndexOf(File.separator);
              return (index != -1 && index != filename.length()-1) ?
                                                 filename.substring(index+1) :
                                                 filename;
         public void explore() {
              if(!isDirectory())
                   return;
              if(!isExplored()) {
                   File file = getFile();
                   File[] children = file.listFiles();
                   for(int i=0; i < children.length; ++i)
                        add(new FileNode(children[i]));
                   explored = true;
    class GJApp extends WindowAdapter {
         static private JPanel statusArea = new JPanel();
         static private JLabel status = new JLabel(" ");
         public static void launch(final JFrame f, String title,
                                       final int x, final int y,
                                       final int w, int h) {
              f.setTitle(title);
              f.setBounds(x,y,w,h);
              f.setVisible(true);
              statusArea.setBorder(BorderFactory.createEtchedBorder());
              statusArea.setLayout(new FlowLayout(FlowLayout.LEFT,0,0));
              statusArea.add(status);
              status.setHorizontalAlignment(JLabel.LEFT);
              f.setDefaultCloseOperation(
                                       WindowConstants.DISPOSE_ON_CLOSE);
              f.addWindowListener(new WindowAdapter() {
                   public void windowClosed(WindowEvent e) {
                        System.exit(0);
         static public JPanel getStatusArea() {
              return statusArea;
         static public void updateStatus(String s) {
              status.setText(s);
    Thanks in advance.

    Hi Paul,
    sorry for my late reply, but I usually don't work on weekends (this time it was an exception).
    OK, then, to your problem:
    - at the first look I thought you did NOT follow all the instruction (namely, the constructor of your trees has no info that you want to use model, or whatsoever), but later I realized that your approach: create the tree first and then assign a model to it (or in fact, get the model from the tree via: tree.getModel()) might work as well
    - having no debugger I am not able to have much clue about your program / and it seems that you coding suffers from your being in a hurry:
    - no comments - don't know which method is expected to do what
    - misleading names (createTreeModel does nothing with the model, but creates some new nodes??)
    therefore, I'm sorry, but I'm not able to detect exactly where the error is.
    - anyway, having a quick glance on your code I have some suspections:
    - you have 2 trees (treeLeft, treeRight), but just one model (model)
    ( it seems that you assign it dynamically when needed - either you take the model of the left or of the right tree)
    - however, when this assignment takes place (in createTestTree()), you DO NOT ASSIGN IT to the class' protected attribute model, but to a local variable model (of the same type, however - since you introduce it as:
    DefaultTreeModel model you override the model from class' attributes) - therefore, your assignment is no valid when the block in which ot is located is finished
    - note, that you NEED the model when you add/delete nodes of the tree (somewhere in DnDTree? - then quite probably your local assignment of model is not valid any longer)
    My suggestion, therefore, is:
    somehow try to encapsulate the model to your tree (note that I only created the model outside the tree, because I needed it for running the constructor, but all other usages of the model are made WITHIN the class of the tree) - the best, do it the same way - through the constructor
    then, in the place when you insert/remove nodes you will have no problem at all
    I will e-mail you my whole "project" so that you may observe all parts - how it's written. I trust if you can't figure it out from my writings here (maybe I missed the point) you may get it from that example.
    Hope it helps - GOOD LUCK

  • How to use JTree?

    hi,
    I need of an object that allows me to choose a directory path, and I think JTree do this.
    But I never have used it;
    I have read Java tutorial, but I don't know how to do to show in JTree my hard disk partition and directory.
    Then, I must create a class that manages JTree or I can create it directly where it is needed?
    Do Can you post me some code line showing the correct use of it?
    Thanks.

    Look at this, and copy what you need
    import java.awt.*;
    import java.awt.event.*;
    import java.awt.geom.*;
    import java.util.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.tree.DefaultTreeCellRenderer;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreePath;
    import java.io.*;
    public class TreeSP extends JFrame implements ActionListener
         JTree              jtR;
         JTree              jtL;
         JSplitPane        jsP1,jsP2;
         JScrollPane        jsL;
         JScrollPane     jsR;
         JButton               jbc,jbd;
         Tpan               panel  = new Tpan();
         int                  from   = -1;
         int                  mark   = -1;
         Point                 toP    = new Point(0,0);
         Vector          frV    = new Vector();
         Vector          toV    = new Vector();
         DefaultTreeCellRenderer tcl = new MyTreeCellRenderer();
    public TreeSP() 
         setBounds(1,1,700,400);     
         getContentPane().setLayout(new BorderLayout());
         addWindowListener(new WindowAdapter()
         {     public void windowClosing(WindowEvent ev)
              {     dispose();
                   System.exit(0);
         LeftTree();
         RightTree();
         jsL = new JScrollPane(jtL);
         jsL.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
         jsR = new JScrollPane(jtR);
         addAdjustmentListener(jsR);
         addAdjustmentListener(jsL);
         JPanel stam = new JPanel();
         stam.addMouseListener(new MouseAdapter()     
         {     public void mousePressed(MouseEvent m)
                   panel.findLine(m.getX(),m.getY());
         jsP2 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,stam,jsR);
         jsP1 = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,jsL,jsP2);
         jsP2.setBorder(null);
         jsP1.setDividerSize(8);
         jsP2.setDividerSize(10);
         jsP2.setDividerLocation(190);
         panel.add("Center",jsP1);
         getContentPane().add("Center",panel);
         JPanel butt = new JPanel();
         butt.setPreferredSize(new Dimension(0,25));
         butt.setLayout(new GridLayout(0,5,10,10));     
         butt.setBorder(new EmptyBorder(4,1,0,0));
         getContentPane().add("South",butt);
         jbc = new JButton("Connect");
         butt.add(jbc);
         jbc.addActionListener(this);
         jbd = new JButton("DisConnect");
         butt.add(jbd);
         jbd.addActionListener(this);
         setVisible(true);     
    private void addAdjustmentListener(JScrollPane jsp)
         jsp.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener()
         {     public void adjustmentValueChanged(AdjustmentEvent a)
                   panel.repaint();
         jsp.getHorizontalScrollBar().addAdjustmentListener(new AdjustmentListener()
         {     public void adjustmentValueChanged(AdjustmentEvent a)
                   panel.repaint();
    public void actionPerformed(ActionEvent ae)
         if (ae.getSource() == jbc) connect();
         if (ae.getSource() == jbd)
              if (mark > -1 && panel.calculateLine(mark)) 
                   frV.remove(mark);
                   toV.remove(mark);
                   mark = -1;
                   panel.repaint();
              else(disConnect());
    private void doNode(DefaultMutableTreeNode aba, File ifile)
         String[] progs = ifile.list();
         for (int pri=0; pri < progs.length; pri++)
              File f = new File(ifile.getPath()+"/"+progs[pri]);
              if (f.isFile())
                   aba.add(new DefaultMutableTreeNode(f.getName()));
              if (f.isDirectory())
                   if (f.isHidden())
    //                    aba.add(new DefaultMutableTreeNode("Hd> "+file));
                   else
                        DefaultMutableTreeNode dry = new DefaultMutableTreeNode(f.getName());
                        aba.add(dry);
                        doNode(dry,f);
    private void LeftTree()
         File file = new File(System.getProperty("user.dir"));     
         DefaultMutableTreeNode rot = new DefaultMutableTreeNode(file.getAbsolutePath());
         doNode(rot,file);
         jtL = new JTree(rot);  
         jtL.setCellRenderer(tcl);
         jtL.putClientProperty("JTree.lineStyle", "Angled");
         jtL.addMouseListener(new MouseAdapter()     
         {     public void mousePressed(MouseEvent m)
                   from  = jtL.getClosestRowForLocation(m.getX(),m.getY());
                   toP.setLocation(-1,-1);
                   jtL.setSelectionRow(from);
                   panel.repaint();
              public void mouseReleased(MouseEvent m)
                   int x = m.getX() - jsR.getX() + 4;
                   Rectangle vl = jsL.getViewport().getViewRect();     
                   Rectangle vr = jsR.getViewport().getViewRect();     
                   if (x > 1)
                          int t = jtR.getClosestRowForLocation(x,m.getY()-vl.y+vr.y);
                        jtR.setSelectionRow(t);
                        connect();     
                   from = -1;
                   panel.repaint();
         jtL.addMouseMotionListener(new MouseMotionAdapter()          
         {     public void mouseDragged(MouseEvent m)
                   if (from > -1)
                        toP.setLocation(m.getX()+4+12,m.getY()+2);
                        panel.repaint();
    private void RightTree()
         File file = new File(System.getProperty("user.dir"));     
         DefaultMutableTreeNode rot = new DefaultMutableTreeNode(file.getAbsolutePath());
         doNode(rot,file);
         jtR = new JTree(rot);  
         jtR.setBorder(new EmptyBorder(0,12,0,0));
         jtR.setCellRenderer(tcl);
         jtR.addMouseListener(new MouseAdapter()     
         {     public void mousePressed(MouseEvent m)
                   panel.repaint();
              public void mouseReleased(MouseEvent m)
                   panel.repaint();
    private void connect()
         TreePath fl = jtL.getPathForRow(jtL.getMinSelectionRow());
         TreePath fr = jtR.getPathForRow(jtR.getMinSelectionRow());
         if (fl == null || fr == null) return;
         frV.add(fl);
         toV.add(fr);
         panel.repaint();
    private void disConnect()
         TreePath fl = jtL.getPathForRow(jtL.getMinSelectionRow());
         TreePath fr = jtR.getPathForRow(jtR.getMinSelectionRow());
         if (fl == null || fr == null) return;
         frV.remove(fl);
         toV.remove(fr);
         panel.repaint();
    public class Tpan extends JPanel
         Rectangle    ll;
         Rectangle    rr;
    public Tpan()
         setLayout(new BorderLayout());
    private void findLine(int x, int y)
         x = x + jsP2.getX();
         for (int k=0; k < frV.size(); k++)
              if (calculateLine(k))
                   Rectangle vl = jsL.getViewport().getViewRect();     
                   Rectangle vr = jsR.getViewport().getViewRect();     
                   Line2D line = new Line2D.Double(ll.x,ll.y-vl.y,rr.x,rr.y-vr.y);
                   if (line.ptLineDist(x,y) < 2)
                        mark = k;
                        repaint();
                        return;
         if (mark != -1)     
                   mark = -1;
                   repaint();
    public void paint(Graphics g)
         super.paint(g);
         myPaint(g);     
    public void myPaint(Graphics g1)
         g1.setColor(Color.black);
         Graphics2D g = (Graphics2D)g1;
         g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);          
         for (int k=0; k < frV.size(); k++)
              if (calculateLine(k))
                   Rectangle vl = jsL.getViewport().getViewRect();     
                   Rectangle vr = jsR.getViewport().getViewRect();     
    //               if (vl.contains(1,ll.y) || vr.contains(1,rr.y))
                        if (k == mark)      g.setColor(Color.red);
                             else        g.setColor(Color.black);     
                        int o = getOfset(frV.get(k)); 
                        g.drawLine(o,ll.y-vl.y,ll.x,ll.y-vl.y);
                        g.drawLine(ll.x,ll.y-vl.y,rr.x,rr.y-vr.y);
                        int l = getEnd(toV.get(k));
                        g.fillRect(rr.x,rr.y-vr.y,l,1);
                        g.drawLine(rr.x+l,rr.y-vr.y-2,rr.x+l+7,rr.y-vr.y);
                        g.drawLine(rr.x+l,rr.y-vr.y+2,rr.x+l+7,rr.y-vr.y);
         g.setColor(Color.gray);     
         if (from > -1 && toP.x > -1)
              Rectangle ll = jtL.getRowBounds(from);
              Rectangle vl = jsL.getViewport().getViewRect();
              ll.x = getStart();
              ll.y = ll.y + ll.height/2 - vl.y + 1;
              g.drawLine(ll.x,ll.y,toP.x,toP.y-vl.y);
    private boolean calculateLine(int k) // to calculate the line Points in Tpan
         TreePath f1 = (TreePath)frV.get(k);
         if (f1 == null) return(false);
         ll   = jtL.getPathBounds(f1);
         ll.x = jsL.getX()+jsL.getWidth();
         ll.y = ll.y + ll.height/2 + 2;
         TreePath f2 = (TreePath)toV.get(k);     
         if (f2 == null) return(false);
         rr   = jtR.getPathBounds(f2);
         rr.y = rr.y + rr.height/2 + 2;
         rr.x = jsP2.getX()+jsP2.getDividerLocation()+jsP2.getDividerSize()-1;
         return(true);
    private int getOfset(Object o) // to calculate where to start the horizntal
    {                              // line on the left side
         Rectangle r = jtL.getPathBounds((TreePath)o);
         Point     p = jsL. getViewport(). getViewPosition();
         int       n = Math.max(0,r.x + r.width - p.x);
         if (jsL.getVerticalScrollBar().isVisible()) n = n+18;
         if (jsL.getWidth() < n) n = jsL.getWidth();
         return(n);
    private int getStart()        // to calculate where to start the draging line
         TreePath f = jtL.getPathForRow(jtL.getMinSelectionRow());
         return(getOfset(f));
    private int getEnd(Object o)  // to calculate where to end the horizontal
    {                                     // ot the right side
         Rectangle r = jtR.getPathBounds((TreePath)o);
         Point     p = jsR. getViewport().getViewPosition();
         int       n = Math.max(0,r.x - p.x - 7);
         return(n);
    public class MyTreeCellRenderer extends DefaultTreeCellRenderer
         ImageIcon   i1   = new ImageIcon("attribute.gif");
         ImageIcon   i2   = new ImageIcon("condition.gif");
    public MyTreeCellRenderer()
         super();
         setFont(new Font("",1,11));
         super.setLeafIcon(i1);
         super.setOpenIcon(i2);
    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);
         return(this);     
    public static void main (String[] args)
         new TreeSP();
    }      Noah

  • Color of parent/child lines in JTree

    Hi,
    i am using a JTree with a custom CellRenderer. This works quite ok but i also want to change the color from the fine lines between parent and child nodes. Right now they are in the typical "SUN" color but cause of my background i need them to be black.
    node
    |
    |--- child1
    |
    |--- child2
    I mean the lines which i just drawn in ASCII Art, really dont know the english word for it.
    Thx

    i am not weird, i am replying to myself, because perhaps someone might need it afterwards.
    you can change the color of the lines between nodes in JTree, therefore you must go the UIManager way:
    UIManager.put("Tree.hash", new ColorUIResource(Color.lightGray));
    This changes all Trees in your application. You can do similar changes on instance basis:
    myJTree.putClientProperty("JTree.lineStyle", "Angled");
    but i havnt figured out why i cant do this for the "Tree.hash" key on instance basis but anyway. Its ok now...

  • JTree Sub Folder of Tree Expanding Incorrectly

    The first time I try to expand a node It gets Expanded. But then when I try to expand the subfolders It does not happen. I am simply not understanding how to go about. The program based on the lines of the 2nd Example of Java Swing 2nd edition(Mathew Robinson) of the Trees Chapter
    import java.awt.BorderLayout;
    import java.io.File;
    import java.util.Vector;
    import javax.swing.Icon;
    import javax.swing.ImageIcon;
    import javax.swing.JFrame;
    import javax.swing.JScrollPane;
    import javax.swing.JTextField;
    import javax.swing.JTree;
    import javax.swing.SwingUtilities;
    import javax.swing.event.TreeExpansionEvent;
    import javax.swing.event.TreeExpansionListener;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.TreeSelectionModel;
    public class FileSystemTree extends JFrame {
         public static final ImageIcon iconComputer = new ImageIcon("computer.gif");
         public static final ImageIcon iconDisk = new ImageIcon("disk.gif");
         private JTree jtree = null;
         private DefaultTreeModel defaultTreeModel = null;
         private JTextField jtfStatus;
         public FileSystemTree() {
              super("FileSystem Tree");
              setSize(500, 500);
              DefaultMutableTreeNode root = new DefaultMutableTreeNode(
                        new NodeIconData(iconComputer, null, "My Comp"));
              DefaultMutableTreeNode node;
              File[] roots = File.listRoots(); //Different disk Drives for the System
              for (int i = 0; i < roots.length; i++) {
                   node = new DefaultMutableTreeNode(new NodeIconData(iconDisk, null,
                             new FileNode(roots)));
                   root.add(node);
                   node.add(new DefaultMutableTreeNode(new Boolean(true)));
              defaultTreeModel = new DefaultTreeModel(root);
              jtree = new JTree(defaultTreeModel);
              jtree.getSelectionModel().setSelectionMode(
                        TreeSelectionModel.SINGLE_TREE_SELECTION);
              jtree.putClientProperty("JTree.linestyle", "Angled");
              jtree.addTreeExpansionListener(new FSDirectoryExpansionListener());
              jtree.setShowsRootHandles(true);
              jtree.setEditable(false);
              jtfStatus = new JTextField();
              jtfStatus.setEditable(false);
              getContentPane().add(new JScrollPane(jtree), BorderLayout.CENTER);
              getContentPane().add(jtfStatus, BorderLayout.SOUTH);
              setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
              setVisible(true);
         DefaultMutableTreeNode getTreeNode(TreePath path) {
              return (DefaultMutableTreeNode) path.getLastPathComponent();
         FileNode getFileNode(DefaultMutableTreeNode node) {
              if (node == null) {
                   return null;
              Object obj = node.getUserObject();
              if (obj instanceof NodeIconData) {
                   obj = ((NodeIconData) obj).getObject();
              if (obj instanceof FileNode) {
                   return (FileNode) obj;
              } else {
                   return null;
         class FSDirectoryExpansionListener implements TreeExpansionListener {
              public void treeCollapsed(TreeExpansionEvent event) {
              public void treeExpanded(TreeExpansionEvent event) {
                   final DefaultMutableTreeNode node = getTreeNode(event.getPath());
                   final FileNode fileNode = getFileNode(node);
                   Thread runner = new Thread() {
                        public void run() {
                             if (fileNode != null && fileNode.expand(node)) {
                                  Runnable runnable = new Runnable() {
                                       public void run() {
                                            defaultTreeModel.reload(node);
                                  SwingUtilities.invokeLater(runnable);
                   runner.start();
         public static void main(String args[]) {
              new FileSystemTree();
    class NodeIconData {
         private Icon normalIcon;
         private Icon expandedIcon;
         private Object data;
         public NodeIconData(Icon icon, Object data) {
              this.normalIcon = icon;
              this.expandedIcon = null;
              this.data = data;
         public NodeIconData(Icon icon, Icon expandedIcon, Object data) {
              this.normalIcon = icon;
              this.expandedIcon = expandedIcon;
              this.data = data;
         public Object getObject() {
              return data;
         public Icon getExpandedIcon() {
              return (expandedIcon != null ? expandedIcon : normalIcon);
         public Icon getNormalIcon() {
              return normalIcon;
         public String toString() {
              return data.toString();
    class FileNode {
         protected File file;
         public FileNode(File file) {
              this.file = file;
         public File getFile() {
              return file;
         public String toString() {
              return file.getName().length() > 0 ? file.getName() : file.getPath();
         public boolean expand(DefaultMutableTreeNode parent) {
              DefaultMutableTreeNode flag = (DefaultMutableTreeNode) parent
                        .getFirstChild();
              if (flag == null) // No flag
                   return false;
              Object obj = flag.getUserObject();
              if (!(obj instanceof Boolean))
                   return false; // Already expanded
              parent.removeAllChildren(); // Remove Flag
              File[] files = listFiles();
              if (files == null)
                   return true;
              Vector v = new Vector();
              for (int k = 0; k < files.length; k++) {
                   File f = files[k];
                   if (!(f.isDirectory()))
                        continue;
                   FileNode1 newNode = new FileNode1(f);
                   boolean isAdded = false;
                   for (int i = 0; i < v.size(); i++) {
                        FileNode1 nd = (FileNode1) v.elementAt(i);
                        if (newNode.compareTo(nd) < 0) {
                             v.insertElementAt(newNode, i);
                             isAdded = true;
                             break;
                   if (!isAdded)
                        v.addElement(newNode);
              for (int i = 0; i < v.size(); i++) {
                   FileNode1 nd = (FileNode1) v.elementAt(i);
                   IconData idata = new IconData(DirTree.ICON_FOLDER,
                             DirTree.ICON_EXPANDEDFOLDER, nd);
                   DefaultMutableTreeNode node = new DefaultMutableTreeNode(idata);
                   parent.add(node);
                   if (nd.hasSubDirs())
                        node.add(new DefaultMutableTreeNode(new Boolean(true)));
              return true;
         public boolean hasSubDirs() {
              File[] files = listFiles();
              if (files == null) {
                   return false;
              for (int i = 0; i < files.length; i++) {
                   if (files[i].isDirectory()) {
                        return true;
              return false;
         public int compareTo(FileNode toCompare) {
              return file.getName().compareToIgnoreCase(toCompare.file.getName());
         public File[] listFiles() {
              if (!(file.isDirectory())) {
                   return null;
              try {
                   return file.listFiles();
              } catch (Exception e) {
                   e.printStackTrace();
                   return null;

    Try this one:
    * FileTree.java
    * author: roar
    import java.io.FileFilter;
    import java.io.*;
    import java.util.List;
    import java.util.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import javax.swing.border.*;
    import javax.swing.tree.*;
    import javax.swing.event.*;
    import javax.swing.filechooser.*;
    public class FileTree extends JTree implements TreeWillExpandListener {
        private static class FileComparator implements Comparator<File> {
            public int compare(File f1, File f2) {
                if (f1.isDirectory() ^ f2.isDirectory()) {
                    return (f1.isDirectory() ? -1 : 1);
                return f1.getName().compareToIgnoreCase(f2.getName());
        private static class DirectoryFilter implements FileFilter {
            public boolean accept(File f) {
                return f.isDirectory();
        private static class AcceptAllFilter implements FileFilter {
            public boolean accept(File f) {
                return true;
        private static final Comparator<File> FILE_COMPARATOR = new FileComparator();
        /** A FileFilter, that accepts directories only */
        public static final FileFilter DIRECTORY_FILTER = new DirectoryFilter();
        /** A FileFilter that accepts all types of files and directories*/
        public static final FileFilter ACCEPT_ALL_FILTER = new AcceptAllFilter();
        /** The current FileFilter */
        protected FileFilter filter = null;
        public FileTree() {
            // look for home directory
            File homeDir = FileSystemView.getFileSystemView().getHomeDirectory();
            // set root element
            DefaultMutableTreeNode root = new DefaultMutableTreeNode(homeDir);
            // set model with root
            DefaultTreeModel model = new DefaultTreeModel(root);
            setModel(model);
            setShowsRootHandles(true);
            // set TreeCellRenderer.
            setCellRenderer(new FileTreeRenderer());
            // expand root
            expandPath(root);
            // add listener
            addTreeWillExpandListener(this);
            // etc ...
            getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
         * Expands a path in the tree.
         * @param d The parent node
        private void expandPath(final DefaultMutableTreeNode d) {
            d.removeAllChildren();
            File[] tempf = ((File) d.getUserObject()).listFiles();
            List<File> files = Arrays.asList(tempf);
            Collections.sort(files, FILE_COMPARATOR);
            DefaultMutableTreeNode temp = null;
            for (File file : files) {
                if (filter != null && !filter.accept(file)) {
                    continue;
                temp = new DefaultMutableTreeNode(file);
                if (file.isDirectory()) {
                    temp.add(new DefaultMutableTreeNode(null));
                d.add(temp);
            ((DefaultTreeModel) getModel()).reload(d);
         * Sets the FileFilter and resets the tree.
         * @param f The new FileFilter
        public void setFileFilter(FileFilter f) {
            filter = f;
            expandPath((DefaultMutableTreeNode) getModel().getRoot());
         * Returns the current FileFilter
         * @return The FileFilter
        public FileFilter getFileFilter() {
            return filter;
        public File getSelectedFile() {
            TreePath selectionPath = getSelectionPath();
            if (selectionPath == null) {
                return null;
            DefaultMutableTreeNode node = (DefaultMutableTreeNode) selectionPath.getLastPathComponent();
            return (File) node.getUserObject();
        public void treeWillCollapse(TreeExpansionEvent e) {
            ((DefaultMutableTreeNode) (e.getPath().getLastPathComponent())).removeAllChildren();
            ((DefaultMutableTreeNode) (e.getPath().getLastPathComponent())).add(new DefaultMutableTreeNode(null));
        public void treeWillExpand(TreeExpansionEvent e) {
            expandPath((DefaultMutableTreeNode) (e.getPath().getLastPathComponent()));
        public static void main(String[] args) throws Exception {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            final JFrame f = new JFrame("Choose File");
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            final FileTree chooser = new FileTree();
            chooser.setFileFilter(FileTree.DIRECTORY_FILTER);
            JScrollPane scrp = new JScrollPane(chooser);
            Border empty = BorderFactory.createEmptyBorder(5, 5, 2, 5);
            scrp.setBorder(BorderFactory.createCompoundBorder(empty, scrp.getBorder()));
            JPanel bottom = new JPanel(new FlowLayout(FlowLayout.RIGHT));
            bottom.add(new JButton(new AbstractAction("OK") {
                public void actionPerformed(ActionEvent e) {
                    File file = chooser.getSelectedFile();
                    String s = "'" + file + "'";
                    if (file == null) {
                        s = "nothing";
                    JOptionPane.showMessageDialog(f, "There was " + s + " selected.");
                    f.dispose();
            f.add(scrp);
            f.add(bottom, BorderLayout.SOUTH);
            f.setSize(300, 400);
            f.setLocationRelativeTo(null);
            f.setVisible(true);
    class FileTreeRenderer extends DefaultTreeCellRenderer {
        private FileSystemView fsv = FileSystemView.getFileSystemView();
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded,
                boolean leaf, int row, boolean hasFocus) {
            super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
            Object user = ((DefaultMutableTreeNode) value).getUserObject();
            if (user instanceof File) {
                File f = (File) user;
                String name = f.getName();
                setIcon(fsv.getSystemIcon(f));
                setText(fsv.getSystemDisplayName(f));
            return this;
    }You can also use ACCEPT_ALL_FILTER;
    chooser.setFileFilter(FileTree.ACCEPT_ALL_FILTER);Edited by: Andre_Uhres on Jan 27, 2008 10:02 AM

Maybe you are looking for

  • -ve values when using record mode in ODS delta

    Hi We have an ODS where we are calculating the number of items using update routine.  I'm not sure if the below code is correct. I'm getting -ve values in my item count for delta loads from ODS to cube. ODS data (active) looks correct. But Cube data

  • Getting error while installing update for Windows 10

    Hi, I am getting below error message while installing window 10 preview using window update option. Please help me how to address this issue to install window 10 preview OS : Windows 7 Enterprise SP1 64 bit Upgrade to Windows Technical Preview for En

  • Adobe Download Assistant Extracting for hours

    Spent 12 hours downloading Photoshop CS5.1 only to find that ADA is now extracting with no indication of how long it will take to complete  (my 30 day trial starts today and I can't access the application). The folder where Photoshop is supposed to d

  • Cisco ISE Distributed environment question

    Hi everyone, We want to deploy the ISE's nodes in primary- secondary to high availability. One Node is in Europe and the another node is in America. Is there exist some restriction about the distance or times, to syncronize between each one?. Of cour

  • Scam emails that appear to come from apple?

    Recently received an email from 'Apple' as an alert stating my account was accessed from a device that had never been used before and that the device was in Indonesia... Obviously rings alarm bells but the email just doesn't 'look' right to me. I've