Niklas R
Niklas R

Reputation: 16900

DefaultMutableTreeNode icon

I have a JTree displayed in a JContentPane built from DefaultMutableTreeNode objects. The tree is intented to display the local file-system. The data should be loaded on request, therefore when the user wants to expand it. This works well, but as long as there are no child items in the node, it displays a file-icon, and turns into a folder-icon when child items have been inserted.

How can I make the node display a folder-icon always, although there are (yet) no child items?

Upvotes: 0

Views: 1982

Answers (3)

dmolony
dmolony

Reputation: 1135

I use this:

DefaultMutableTreeNode root = new DefaultMutableTreeNode ();
DefaultTreeModel treeModel = new DefaultTreeModel (root);
tree = new JTree (treeModel);
addFiles (root);                            // build the catalog tree recursively
treeModel.setAsksAllowsChildren (true);     // allows empty nodes to appear as folders

with

if (file.isDirectory ())
  newNode.setAllowsChildren (true);

in the addFiles() routine. The setAsksAllowsChildren(true) needs to come after the tree is built.

Upvotes: 1

kleopatra
kleopatra

Reputation: 51536

Using a DefaultMutableTreeNode (or a custom implementation of TreeNode), the means to distinguish files from empty folders is its allowsChildren property:

// get a list of files
File[] files = new File(".").listFiles();
// configure the nodes' allowsChildren as the isDir of the File object
for (File file : files) {
    root.add(new DefaultMutableTreeNode(file, file.isDirectory()));
}          
// configure the TreeModel to use nodes' allowsChildren property to
// decide on its leaf-ness
DefaultTreeModel model = new DefaultTreeModel(root, true);

Upvotes: 1

Sergiy Medvynskyy
Sergiy Medvynskyy

Reputation: 11327

You need to implement cell renderer for your tree. So you can define icon for the node. See here the sample for a table (tree also has method setCellRenderer)

Upvotes: 2

Related Questions