Best way to stop a JTree selection change from happening?

前端 未结 7 2170
傲寒
傲寒 2021-01-06 05:07

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

7条回答
  •  伪装坚强ぢ
    2021-01-06 05:26

    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());
    }
    

提交回复
热议问题