Jtree仅选择子节点而不是父节点

时间:2014-08-20 05:58:52

标签: java swing jtree

我正在使用一个Jtree,我被困在一个地方做下面的事情,

Diagram

来自图:2 I click on A(Check box) and all its child is getting selected - It's fine

来自图3 I Clicked D(CheckBox) and all its parents (A,B,C) are also geting selected.

现在我想做的是,

If i select A -> A,B,C,D will eb selected
If i Select B-> only B,C,D
If c -> C,D
If D-> Only D

我使用的代码是:

public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus){ 

                //delegate is TreeCellrenderer
                Component renderer = delegate.getTreeCellRendererComponent(tree, value, selected, expanded, leaf, row, hasFocus); 
                TreePath path = tree.getPathForRow(row);
                if(path!=null)
                {         
                    //Selection Model is TreeSelection Model
                    if(selectionModel.isPathSelected(path, true)) //Below code.
                    {       
                        checkBox.setState(checkBox.SELECTED);   
                        if (selected) 
                        {
                            //Comes here If check box is selected by mouse click
                        }
                    }
                    else
                    {                       
                        checkBox.setState(checkBox.NOT_SELECTED);   
                    }
                } 
                add(checkBox, BorderLayout.WEST); 
                add(renderer, BorderLayout.CENTER);  
                return this; 
            }

isPathSelected方法:

// tells whether given path is selected. 
        // if dig is true, then a path is assumed to be selected, if 
        // one of its ancestor is selected. 
        public boolean isPathSelected(TreePath path, boolean dig){                      
            if(!dig){
                return super.isPathSelected(path); 
            }

            while(path!=null && !super.isPathSelected(path)){
                path = path.getParentPath(); 
            }

            return path!=null; 
        } 

我不确定是不是对Jtree来说是新手。请帮忙

1 个答案:

答案 0 :(得分:1)

你必须走过'树元素中的子节点:

public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, boolean leaf, int row, boolean hasFocus){
    DefaultMutableTreeNode node = (DefaultMutableTreeNode) value;
    walkThroug(node, isSelected);
}

private void walkThrough(DefaultMutableTreeNode node, boolean isSelected) {
    int cc = node.getChildCount();

    //TODO select current node
    //something like: node.setSelected(isSelected)

    for(int i = 0; i < cc; i++){
        DefaultMutableTreeNode childNode = (DefaultMutableTreeNode) node.getChildAt(i);
        walkThrough(childNode, isSelected);
    }
}

这是一个递归调用,它只是一个片段,但它应该以这种方式工作......也许它需要一些其他的参数在&#39; walkThrough&#39; -methode ... < / p>

我断言您的对象(值)是http://docs.oracle.com/javase/tutorial/uiswing/components/tree.html

中描述的DefaultMutableTreeNode