I have a JTree with a custom TreeCellRenderer.
DefaultMutableTreeNode myTreeRoot = new DefaultMutableTreeNode();
JTree myTree = new JTree(myTreeRoot);
myTree.setCellRenderer(new DefaultTreeCellRenderer() {
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) {
if (((DefaultMutableTreeNode) value).getUserObject() instanceof MyObject) {
System.out.println("============= my object ===========" + value);
}
return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
}
});
Then I add the nodes to the tree dynamically after it displayed. Consider the case of adding only one child.
MyObject object = new MyObject("Child Node");
DefaultMutableTreeNode myTreeNode = new DefaultMutableTreeNode(object);
myTreeRoot.add(myTreeNode);
Then I hide tree root as well
myTree.expandRow(0);
myTree.setRootVisible(false);
myTree.setShowsRootHandles(true);
if (myTreeRoot.getChildCount() != 0) {
myTree.setSelectionRow(0);
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
devicesTree.updateUI();
}
});
Laterly there is another option to remove these nodes
private void removeNode(MyObject object) {
DefaultMutableTreeNode myTreeNode = getTreeeNode(object); //This method traverse through the tree and returns the corresponding node
DefaultMutableTreeNode selectedNode = (DefaultMutableTreeNode) myTree.getSelectionPath().getLastPathComponent();
int selectedRow = -1;
if (myTree.getSelectionRows().length > 0) {
selectedRow = myTree.getSelectionRows()[0];
}
boolean isSelected = selectedNode == myTreeNode;
if (isSelected) {
if (myTree.getRowCount() == 1) {
myTree.clearSelection();
} else if (myTree.getRowCount() > selectedRow + 1) {
myTree.setSelectionRow(selectedRow + 1);
} else if (selectedRow != 0) {
myTree.setSelectionRow(0);
}
}
DefaultMutableTreeNode parent = (DefaultMutableTreeNode) myTreeNode.getParent();
parent.remove(myTreeNode);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
myTree.updateUI();
}
});
}
Now the problem I have is when there is only one child at the root of the tree and if I chosen to remove that child, after the removal getTreeCellRendererComponent() method still points to that removed object. Is there any clue for that?