manipulate jtree node via references seems not working (swing)

喜夏-厌秋 提交于 2019-12-11 09:57:05

问题


I have the following problem (this is related to my post blink a tree node):
I have a custom cell renderer.
In some part of my code I create a new DefaultMutableTreeNode and store it in a list

public static List<DefaultMutableTreeNode> nodes = new ArrayList<DefaultMutableTreeNode>() 
//in some time
DefaultMutableTreeNode aNode = new DefaultMutableTreeNode("SomeValue");
nodes.add(node);

In my cell renderer I do:

public Component getTreeCellRendererComponent(JTree tree, Object value,
      boolean selected, boolean expanded, boolean leaf, int row,
      boolean hasFocus) {
    DefaultMutableTreeNode n = (DefaultMutableTreeNode)value;
    if(nodes.contains(n)){
     //set background to red
    }
}

At this point nodes has a node but the code never goes in the if branch.
Why? I can not understand since I already stored it in the arraylist. Do I get a different reference?
Also I created a swing timer:

Timer t = new Timer(400, new ActionListener(){
   public void actionPerformed(ActionEvent evt) {
        if(nodes.size == 0)
            return;
        TreePath p = new TreePath(nodes.get(0));
        Rectangle r = tree.getPathBounds(p);
        tree.repaint(r);
   }

});    

But I get a NPE in tree.getPathBounds.
I can not understand why. Can't I manipulate DefaultMutableNodes I stored in my list this way? What am I doing wrong in my thinking?
Note: If I simply call repaint(); in the timer and in the cell renderer I loop over the nodes to see if it displays the sametext with the node I have stored, what I want I get the blinking, works

Thanks


回答1:


Actually TreePath is a list of objects... path from tree root to the node. If you create a path from the single node the path exists in the tree only if the node is root of the tree. I woul recommend to use TreeSelectionEvent public TreePath[] getPaths() method. The method provides actual paths.




回答2:


I don't think DefaultMutableTreeNode defines an equals method, so it might not find the match in your List of nodes. Try storing and searching for the user object or extends DefaultMutableTreeNode and define equals.



来源:https://stackoverflow.com/questions/4511222/manipulate-jtree-node-via-references-seems-not-working-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!