简体   繁体   中英

How to call DefaultTreeCellRenderer for specific nodes in the JTree

I have a customized DefaultTreeCellRenderer that disables nodes in the JTree.

Here is its code:

static class CustomDefaultTreeCellRenderer extends DefaultTreeCellRenderer{
        @Override
        public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus)
        {
            boolean enabled = true; // <-- here is the logic for enable/disable cell


            Component treeCellRendererComponent = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
            treeCellRendererComponent.setEnabled(enabled);
            return treeCellRendererComponent;

        }
}

But I am not able to use it in my code. I cant to have a method or something to call it wherever I need it. For example, when the button is pressed, or when the item has a specific name.

Here is an example that, my method walks through the model and find the node matching with the giver string.

protected void walk(TreeModel model, Object o, String word){
    int  cc;
    cc = model.getChildCount(o);
    for( int i=0; i < cc; i++) {
      Object child = model.getChild(o, i);
      if (model.isLeaf(child) && child.toString().equals(word)){
        System.out.println(child);
        // HERE I NEED TO MAKE "child" DISABLED 
      }
      else {
        walk(model,child, word); 
        }
     }
}

This is how I set the CustomDefaultTreeCellRenderer to my tree:

tree.setCellRenderer(new CustomDefaultTreeCellRenderer());

And this is an example of my walk method:

walk(tree.getModel(), tree.getModel().getRoot(), "DS.png");

So any idea how to disable a specific node?

The Swing framework controls when a TreeCellRenderer is called for a node; you have no control over this. You need to check the condition you need (for example, the name of the node) inside your CustomDefaultTreeCellRenderer. Simply don't call setEnabled() if the node doesn't need to be disabled.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM