JTree with expandable empty parents

766 Views Asked by At

I would like to create a JTree which reflect directory structure but is loaded succesive.

I have dir structure:

c:\root
-------\dir1
------------\file1
------------\file2
-------\dir2

I know how to load to JTree node structure of directories of first level (dir1, dir2). But i don't want to search files in each directory only when user will expand specific node in order to save time and resources.

Because of above i would like to add plus icon (or equivalent for particular java style) to each node even if it will be empty, in order to suggest user in this direcory can be files. Also when user will expand node (and search will be performed) when dir is empty i would like to remove any icon.
Is any way to do it?

1

There are 1 best solutions below

0
On

I think DefaultTreeModel#setAsksAllowsChildren(boolean) is what you are looking for.

Sets whether or not to test leafness by asking getAllowsChildren() or isLeaf() to the TreeNodes. If newValue is true, getAllowsChildren() is messaged, otherwise isLeaf() is messaged.

enter image description here

import java.awt.*;
import javax.swing.*;
import javax.swing.tree.*;

public class AsksAllowsChildrenTest {
  private JComponent makeUI() {
    DefaultTreeModel model = makeDefaultTreeModel();
    model.setAsksAllowsChildren(true);

    JPanel p = new JPanel(new GridLayout(1, 2));
    p.add(new JScrollPane(new JTree(makeDefaultTreeModel())));
    p.add(new JScrollPane(new JTree(model)));
    return p;
  }
  private static DefaultTreeModel makeDefaultTreeModel() {
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("c:/root");
    DefaultMutableTreeNode dir;

    dir = new DefaultMutableTreeNode("dir1");
    root.add(dir);
    dir.add(new DefaultMutableTreeNode("file1", false));
    dir.add(new DefaultMutableTreeNode("file2", false));

    dir = new DefaultMutableTreeNode("dir2");
    root.add(dir);

    return new DefaultTreeModel(root);
  }
  public static void main(String... args) {
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() {
        createAndShowGUI();
      }
    });
  }
  public static void createAndShowGUI() {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.getContentPane().add(new AsksAllowsChildrenTest().makeUI());
    f.setSize(320, 240);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}