本文介绍了jtree自定义图标帮助的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为文件系统创建树形视图..以便将不同的图标分配给每个节点,我以以下方式覆盖getTreeCellRendererComponent

i''m creeting a tree view for the file system....in order to assgin different icons to each node i''m overriding getTreeCellRendererComponent in the following manner

public Component getTreeCellRendererComponent(JTree tree, Object value,boolean sel, boolean expanded, boolean leaf, int row,boolean hasFocus)
{
  System.out.println("in cell renderer");
  FileSystemView fsv=FileSystemView.getFileSystemView();
  DefaultMutableTreeNode dmtn = (DefaultMutableTreeNode) value;
  File nodefile=(File)dmtn.getUserObject();//i'm getting below mentioned exception here
  Icon icon;
  String filename = "";
  if (nodefile != null)
  {
    if (ismynodefilesystem(nodefile))
    {
       if (filename == null)
       {
         filename = fsv.getSystemDisplayName(nodefile);
       }
    }
    else
    {
      filename = nodefile.getName();
    }
  }
  JLabel result = (JLabel) super.getTreeCellRendererComponent(tree,filename, sel, expanded, leaf, row, hasFocus);
  if (nodefile != null)
  {
    icon = fsv.getSystemIcon(nodefile);
    result.setIcon(icon);
  }
  return result;
}


我已经使用setUserObject()将File对象分配给每个节点
我因为以下原因而遇到异常:


i have assigned a File object to each node using setUserObject()
i''m getting an exception as:

Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.io.File<br />
at line:File nodefile=(File)dmtn.getUserObject();<br />


请帮助我使用此代码,并指出我的错误
感谢


please help me with this code and do point out my mistakes
thanks

推荐答案

File nodefile=new File(dmtn.getUserObject());


如果这样做会怎样?

也请检查以下站点: Swing JTree教程 [ ^ ]第5节是关于树上的图标的说明.

尝试以下 [ ^ ]

两者都不会满足您的确切问题-但是有一点创意会使您找到合适的解决方案.


what happens if you do so?

PLease also check this site: Swing JTree Tutorial[^] Section 5 is about the icons on the tree.

try this Showing the file system as a Swing JTree[^]

Both will not meet your exact problem - but with a bit of creativity lead you to a suitable solution.


public Component getTreeCellRendererComponent(JTree tree, Object value,
                boolean sel, boolean expanded, boolean leaf, int row,
                boolean hasFocus)
     {
        System.out.println("value is :"+value.getClass());
        if ((value != null) && (value instanceof DefaultMutableTreeNode)) {
      Object userObject = ((DefaultMutableTreeNode) value)
          .getUserObject();
      System.out.println("node is dmtn");
      if(userObject instanceof File)
      {
          System.out.println("value is file");
          File tempfile=(File)userObject;
         this.setText(tempfile.getName());
          this.setIcon(fsv.getSystemIcon(tempfile));
      }
         }

        return this;
    }


这篇关于jtree自定义图标帮助的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 05:42