manipulate jtree node via references seems not working (swing)
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 listpublic 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
.
Thanks
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.
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.
精彩评论