简体   繁体   English

DefaultMutableTreeNode图标

[英]DefaultMutableTreeNode icon

I have a JTree displayed in a JContentPane built from DefaultMutableTreeNode objects. 我在从DefaultMutableTreeNode对象构建的JContentPane显示了一个JTree 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 ) 请参阅此处的表示例(树也具有setCellRenderer方法)

Using a DefaultMutableTreeNode (or a custom implementation of TreeNode), the means to distinguish files from empty folders is its allowsChildren property: 使用DefaultMutableTreeNode(或TreeNode的自定义实现),将文件空文件夹区分开的方法是它的allowChildren属性:

// 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. 在addFiles()例程中。 The setAsksAllowsChildren(true) needs to come after the tree is built. setAsksAllowsChildren(true)需要在树构建之后出现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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