简体   繁体   中英

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?

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 )

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM