I have a dialog where each entry in a JTree has its corresponding options in a different panel, which is updated when the selection changes. If options for one of the entrie
I did not find a better way, but this approach works fine for me. I know in Delphi it was a very convenient event: "before changing selection" where you could very easily stop changing selection.
here is my java code with prevention of infinite recursion problem
navTree.addTreeSelectionListener(new TreeSelectionListener() {
boolean treeSelectionListenerEnabled = true;
public void valueChanged(TreeSelectionEvent e) {
if (treeSelectionListenerEnabled) {
if (ok to change selection...) {
...
} else {
TreePath treePath = e.getOldLeadSelectionPath();
treeSelectionListenerEnabled = false;
try {
// prevent from leaving the last visited node
navTree.setSelectionPath(treePath);
} finally {
treeSelectionListenerEnabled = true;
}
}
}
}
});
always remember to remove all listeners you added, to prevent memory leaks.
here is another approach:
private class VetoableTreeSelectionModel extends DefaultTreeSelectionModel {
public void setSelectionPath(TreePath path){
if (allow selection change?) {
super.setSelectionPath(path);
}
}
}
{
navTree.setSelectionModel(new VetoableTreeSelectionModel());
}