Filteredtreemodel, how to hide parent nodes if no children

hi. i have surfed and read a lot of posts and topics here regarding filteredtreemodel. some i found hard to understand so i chose to use NiceGuy1's code from long ago since it's the easiest to understand.
package test;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.Enumeration;
public class FilteredTreeModel extends DefaultTreeModel {
    // this hashmap gets the list of pdf files and the filter status
    private String filterText;
    private DefaultMutableTreeNode orig_root;
    public FilteredTreeModel(DefaultMutableTreeNode root) {
        super(root);
        orig_root = root;
    public void setFilterText(String s) {
        this.filterText = s;
        reload();
    public String getFilterText() {
        return this.filterText;
    @Override
    public Object getChild(Object parent, int index) {
        return getFilteredChildren(parent).get(index);
    @Override
    public int getChildCount(Object parent) {
        return getFilteredChildCount(parent);
    @Override
    public int getIndexOfChild(Object parent, Object child) {
        return getFilteredChildren(parent).indexOf(child);
    private int getFilteredChildCount(Object parent) {
        return getFilteredChildren(parent).size();
    private ArrayList<TreeNode> getFilteredChildren(Object parent) {
        ArrayList<TreeNode> filteredChildren = new ArrayList<TreeNode>();
        DefaultMutableTreeNode parentNode = null;
        parentNode = (DefaultMutableTreeNode)parent;
        for (Enumeration e=parentNode.children(); e.hasMoreElements();) {
            DefaultMutableTreeNode nextNode = (DefaultMutableTreeNode) e.nextElement();
            DefaultMutableTreeNode dummy = null;
              if (nextNode.children().hasMoreElements()) {
                  filteredChildren.add(nextNode);
            } else {
                // if node is leaf node
                if (filterText == null ) {
                    // add right away if no filter
                    filteredChildren.add(nextNode);
                } else {
                    // if filter matches this leaf node, add it. if not, how to check if
                    // parent nodes have empty children and remove it.
        return filteredChildren;
}i havent had luck the whole day trying to make this work. it seemed that once the filteredChildren.add() is called, it gets rendered to the treecellrenreder right away so if i wnat to remove the parents (in case it has no children based on the filter),the parent nodes will stay put in the jtree. any workaround? or ideas? i dont want to use a different defaulttreemodel for this. i want to avoid that because i have lots of nodes in my jtree.

Looks like you need this:
for (Enumeration e=parentNode.getFilteredChildren(); e.hasMoreElements();) Edit: okay, that was just a quick guess. Actually you're going to get into trouble if you try to recursively suppress nodes with no children. First you suppress all the leaf nodes (because they naturally don't have any children). Then you suppress all of their parents, because now they don't have any unsuppressed children. Then you suppress all of the parents' parents, because now they don't have any unsuppressed children... and so on until you only have the root left. So you need to refine that requirement.
But I get what you're saying. I had to do a similar thing, only I didn't use a FilteredTreeModel, I just built the TreeModel based on a selection from another tree. It's ridiculously hard to do when you don't get the nodes in order from the database, too, but that's a different problem.

Similar Messages

  • How to hide a node with no children in ADF Tree after Search

    Hi,
    I have a tree component with Search in my screen.
    I followed http://www.jobinesh.com/2010/01/search-by-child-attributes-on-tree.html to implement search.
    Search is performing on the childnodes, once the search is done I am expanding all the nodes and displaying only the filtered records.
    my code to expand all the nodes :
    public void expandAllTreeNodes() {
    UIXTree tree = getGroupTree();
    RowKeySet disclosedRowKeys = new RowKeySetTreeImpl(true);
    CollectionModel model = (CollectionModel)tree.getValue();
    JUCtrlHierBinding treeBinding = (JUCtrlHierBinding)model.getWrappedData();
    JUCtrlHierNodeBinding nodeBinding = treeBinding.getRootNodeBinding();
    List<JUCtrlHierNodeBinding> childNodes = nodeBinding.getChildren();
    if (childNodes != null) {
    for (JUCtrlHierNodeBinding _node : childNodes) {
    disclosedRowKeys.add(_node.getKeyPath());
    disclosedRowKeys.remove(_node.getKeyPath());
    tree.setDisclosedRowKeys(disclosedRowKeys);
    Now I want to hide the nodes which does not have children after search.
    how can I hide the node if _node.getChildren() is null.
    Could any one provide some inputs on this.
    Thanks,
    Swathi

    AE Basics
    Keyframe the mask path.

  • How to make parent node JCheckbox

    How can I make the parent node in
    http://www.java2s.com/Code/Java/Swing-JFC/CheckBoxNodeTreeSample.htm
    to a checkbox.
    Any help is greatly appreciated.
    Regards,
    Anees

    See my example here: [http://forums.sun.com/thread.jspa?threadID=5180008&messageID=9699576]
    If you have a specific problem post a Short, Self Contained, Compilable and Executable, Example Program (SSCCE) that demonstrates the problem.

  • How to hide root node of hierarchy?

    Hi,
    can anyone give me a hint how to hide the root node of a hierarchy?
    Thank you very much in advance, best regards
    Frank

    Hi Frank,
    Another way would be to restrict the hierarchy in the query definition. Select all nodes, except the root. You can do the same in excel and save the query as a view. Of course, you have to maintain this selection every time the hierarchy gets new nodes.
    Natali

  • DMEE : how to make parent node disappear when child node is empty

    Hi Friends ,
    Currently i am working on DMEE , I have a problem . When Child node is empty I donot want the parent node to appear in the tree.Here I am uisng a field via exit function module for childnode. so not a fpay* strucutre field to write a condition.
    Is there any other way for this ?
    Please help.
    Komaravolu

    I'm not sure if this can be done in DMEE tree, but there is BADI DMEE_BADI_01 that can be implemented to perform any kind of postprocessing right before the file is created. I used it, for example, to replace separators with tabs. I believe this can also be used to eliminate the unneeded nodes.

  • How to get Parent nodes and corresponding child nodes in BI Hierarchy

    Hi all,
    I have a standard function module 'RSNDI_SHIE_STRUCTURE_GET3'  to get child node if i pass parent node. But I need child nodes along with the provided parent node as I use this in a loop in BI.
    Thanks

    Could any one help me in this regards .
    Thanks in advance
    Regards,
    sri

  • How to hide parent cost center code in the costing LOV

    Dear Gurus,
    I have a very peculiar issue. I want to hide parent cost center code that appears in the costing LOV of employee in the others tab. Can any body help me out on this one?
    Regards,
    Muhammad Noman Shafique

    Hi,
    I do not have the exact steps for form personalization as I am not good in this :-(
    But regarding the costing segment (removal from all pages) you can follow below steps:-
    1. Navigate to Sysadmin --> Application --> Flexfield --> Segments
    2. Search for title "Cost Allocation Flexfield"
    3. Now click on teh code that is attahed with your business group and then click in segments.
    4. You will see all the segments defiened for the costing.
    NOTE: If you want to disable one of them uncheck the "Freeze Flexfield Definition" in the "Key Flexfield Segments" window. But do remember that it will affect all your costing and you wont be able to select the disabled costing segments in any other window (Element Entries, Assignemnt, Organization, Element link and Payroll)
    Thanks,
    Avinash

  • How to remove parent nodes in an output XML?

    Hi! I'm having a problem as to removing a parent node in an xml output. The scenario goes like this, I have a source IDOC and two target External Definitions. When I have declared the two External Definitions, XI inserted a structure in the output xml as shown below:
    Messages        (1..1)
              Message1       (1..1)
                 Message1Header    (0..1)
              Message2       (1..1)
                 Message2Header    (0..1)
    Is there anyway to have an output that looks just like this (without their respective parent nodes)?
    a.) Message1Header  (0..1)
    or
    b.) Message2Header  (0..1)
    Please help
    Regards,
    Mark

    Since you have two External Definitions and you are using both in on mapping hence your scenario becomes 1:N mapping scenario and this is the reason you are getting the additional nodes in your mapping.
    so if your requirement is 1:N then whatever you are getting is correct, you can refer the below mentioned blog for help on this, But if you don't want the additonal nodes then you have to create TWO different mappings and used the external definitions seprately in each mapping.
    /people/jin.shin/blog/2006/02/07/multi-mapping-without-bpm--yes-it146s-possible
    I hope it helps...

  • How to generate parent node id and child node id from xmltable ?

    Hi All, Below is a part of the xml data which is loaded in a table. I need help in generating the parent id for compensationReference say for the first occurence of compensationReference node it should be 1 and for subsequent nodes 2,3,4,.. Can some one please help me in getting this done using a sql query ??                                                         VID                          9100000013890660                                                        ACN                          5924112896                                                                          VID                          9100000013890678                                                              ACN                          5924112896                                                                                VID                            9100000013890611                                                                    ACN                            5924112896                                                                                        VID                                9100000013890645                                                                          ACN                                  5924112896                              Thanks, Bhaskar

    that doesn't look like XML data to me.
    Please post some correct example data and expected output as described in the FAQ: Re: 2. How do I ask a question on the forums?

  • HOw to get parent node name value through its child node?

    Hi,
    Experts,
    I am able to get child node name values but according to attribute name value i want to  get its parent name value how to achieve that. For that i have used If_Ixml_element->Get_parent. Please pass some idea on it.
    Thanks in advance,
    Shabeer ahmed.

    Hello Shabeer
    I think the coding should be straightforward:
    DATA: lo_element   TYPE REF TO if_ixml_element,
              lo_child        TYPE REF TO if_ixml_node,
              lo_parent      TYPE REF TO if_ixml_node.
    " NOTE: LO_ELEMENT holds your child node
      lo_child ?= lo_element.
      lo_parent = lo_child->get_parent( ).
    Regards
      Uwe

  • How to refer parent node when we are at child element ?

    Hi members, how everbody is fine.
    i have one question.
    i have four group in my template.
    i am doing group total at the end of each group.
    at the end of each group i want to check that if group A then
    store group total in variable XX.
    if that group total for group B thens store group total in variable YY.
    then at the end of group B , after group B total
    i want to subtract group B total from group A total.
    any kinda help is greatly appreciated.
    thanks/

    hi,
    below is my output.
    Grouup 1
    1st year 2nd year
    ------- 1 3
    ------- 10 11
    all elements 5 5
    ------ 2 1
    ------- 4 3
    Total 22 23
    Group 2
    1st year 2nd year
    ------- 5 6
    ------- 9 10
    all elements 2 4
    ------ 1 0
    ------- 11 12
    Total 28 32
    total 28-22=6 32-23=9
    so how can i subtract this above total from group 2 - group 1 ?
    and this same like that if there is group 3 then
    at the end of group 3 - right below of total of group 3
    i need to display group 3 total - group 2 total ..
    thanks.

  • Getting Parent Node using SQL

    Hello,
    I am trying to query an XML which is stored in XMLTYPE datatype column in oracle table. I am using the below SQL:
    select
    EXTRACTVALUE (column_name, '/Person/Customer/Customer_First_Name'),
    EXTRACTVALUE (column_name, '/Person/Customer/Customer_Last_Name'),
    from TABLE_1 A, TABLE ( XMLSEQUENCE (EXTRACT (A.column_name, '/sdi_header//Person')) ) P
    Sample XML:
    <sdi_header>
    <Person>
    <Customer_First_Name>ABC</Customer_First_Name>
    <Customer_Last_Name>DEF</Customer_First_Name>
    </Person>
    <warehouse>
    <Person>
    <Customer_First_Name>XYZ</Customer_First_Name>
    <Customer_Last_Name>MNO</Customer_First_Name>
    </Person>
    </warehouse>
    </sdi_header>
    In the above query the Alias P has a //Person which means I am trying to extract all the repeating person Nodes information in XML. Retrieving all persons is working but I want to extract the parent node information of each Person like for Example in the above sample XML, it has two persons in it
    1) 1 Person is coming under sdi_header node , in such case I need to get <sdi_header/> in SELECT statement
    2) 1 Person is coming under warehouse node , in such case I need to get <warehouse/>in SELECT statement
    How can the parent node information be extracted in SELECT statement.
    Any suggestion/Help is much appreciated.
    Thanks,
    SKM
    Edited by: user9116854 on Mar 1, 2010 10:24 AM
    Edited by: user9116854 on Mar 1, 2010 10:30 AM
    Edited by: user9116854 on Mar 1, 2010 10:35 AM
    Edited by: user9116854 on Mar 1, 2010 10:45 AM
    Edited by: user9116854 on Mar 2, 2010 8:05 AM

    Sounds like you are looking for something like this
    Connected to Oracle Database 11g Enterprise Edition Release 11.1.0.6.0
    SQL> WITH table_1 AS
      2  (SELECT XMLTYPE('<sdi_header>
      3  <Person>
      4  <Customer_First_Name>ABC</Customer_First_Name>
      5  <Customer_Last_Name>DEF</Customer_Last_Name>
      6  </Person>
      7  <warehouse>
      8  <Person>
      9  <Customer_First_Name>XYZ</Customer_First_Name>
    10  <Customer_Last_Name>MNO</Customer_Last_Name>
    11  </Person>
    12  </warehouse>
    13  </sdi_header>') column_name
    14     FROM dual)  -- WITH simulates your table I do not have
    15  select t1.*
    16    from TABLE_1,
    17         XMLTABLE('for $i in /sdi_header//Person
    18                     return <root>
    19                           {$i/Customer_First_Name,
    20                           $i/Customer_Last_Name}
    21                           <parent>{$i/../name()}</parent>
    22                      </root>'
    23                  PASSING table_1.column_name
    24                  COLUMNS
    25                  fname   VARCHAR2(20) PATH 'Customer_First_Name',
    26                  lname   VARCHAR2(20) PATH 'Customer_Last_Name',
    27                  pnode   VARCHAR2(20) PATH 'parent') t1;
    FNAME                LNAME                PNODE
    ABC                  DEF                  sdi_header
    XYZ                  MNO                  warehouseYou can find out how formatted that message by looking in the FAQ in the upper right. It uses the { code } tag (without spaces).

  • Hide a node which itself consist a table

    Hi
    I need to hide a node completely which is binded with a table structure.
    node-table
    attribute-matnr,mtart
    pls tell me how to hide the node - table complete with a code.
    reds

    if u want to hide ur table which is binded to the context  node , u can hide using the attribute wdui_visibility
    u can declare a context attribute of type wdui_visibility and bind its(table's)  VISIBLE property  with this attribute
    set the attribute value to 01 to make the table invisible
       DATA lo_nd_cn_visiblesuper TYPE REF TO if_wd_context_node.
        DATA lo_el_cn_visiblesuper TYPE REF TO if_wd_context_element.
        DATA ls_cn_visiblesuper TYPE wd_this->element_cn_visiblesuper.
        DATA lv_ca_visible LIKE ls_cn_visiblesuper-ca_visible.
    *   navigate from <CONTEXT> to <CN_VISIBLESUPER> via lead selection
        lo_nd_cn_visiblesuper = wd_context->get_child_node( name = wd_this->wdctx_cn_visiblesuper ).
    *   get element via lead selection
        lo_el_cn_visiblesuper = lo_nd_cn_visiblesuper->get_element(  ).
    *   get single attribute
        lo_el_cn_visiblesuper->set_attribute(
          EXPORTING
            name =  `CA_VISIBLE`
            value = '01').
    here I have created a attribute ca_visible under node cn_visiblesuper of type wdui_visibility type ,which I am setting to 01
    to make table invisible this is binded to VISIBLE property of ur table UI
    u can set attribute to 02 in case u want to make ur table visible again
    I hope it shud help
    rgds,
    amit

  • How to hide a tree node from the GUI but still keep it in the tree model?

    Hi, All
    I used a JTree in my project in which I have a DefaultTreeModel to store all the tree structure and a JTree show it on the screen. But for some reason, I want to hide some of the nodes from the user, but I don't want to remove them from the tree model because later on I still need to use them.
    I searched on the web, some people suggested method to hide the root node, but that's not appliable to my project because I want to hide some non-root nodes; Some people also suggested to collapse the parent node when there are child to hide, it is not appliable to me either, because there still some other childnodes (sibling of the node to hide) I want to show.
    How can I hide some of the tree node from the user? Thanks for any information.
    Linda

    Here's an example using a derivation of DefaultTreeModel that shows (or does not show) two types of Sneech (appologies to the good Dr Zeus) by overiding two methods on the model.
    Now, there are many things wrong with this example (using instanceof, for example), but it's pretty tight and shows one way of doing what you want.
    Note: to make it useful, you''d have to change the implementation of setShowStarBelliedSneeches() to do something more sophisticated than simply firing a structure change event on the root node. You'd want to find all the star bellied sneech nodes and call fireTreeNodesRemoved(). That way the tree would stay expanded rather than collapse as it does now.
    import javax.swing.JTree;
    import javax.swing.JScrollPane;
    import javax.swing.JOptionPane;
    import javax.swing.JCheckBox;
    import javax.swing.JPanel;
    import javax.swing.tree.TreePath;
    import javax.swing.tree.DefaultTreeModel;
    import javax.swing.tree.DefaultMutableTreeNode;
    import java.awt.Dimension;
    import java.awt.BorderLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.Enumeration;
    class FilteredTree
         private class PlainBelliedSneech {
              public String toString() { return "Plain Bellied Sneech"; }
         private class StarBelliedSneech {
              public String toString() { return "Star Bellied Sneech"; }
         private class FilteredTreeModel
              extends DefaultTreeModel
              private boolean mShowStarBelliedSneeches= true;
              private DefaultMutableTreeNode mRoot;
              FilteredTreeModel(DefaultMutableTreeNode root)
                   super(root);
                   mRoot= root;
              public Object getChild(Object parent, int index)
                   DefaultMutableTreeNode node=
                        (DefaultMutableTreeNode) parent;
                   if (mShowStarBelliedSneeches)
                        return node.getChildAt(index);
                   int pos= 0;
                   for (int i= 0, cnt= 0; i< node.getChildCount(); i++) {
                        if (((DefaultMutableTreeNode) node.getChildAt(i)).getUserObject()
                                            instanceof PlainBelliedSneech)
                             if (cnt++ == index) {
                                  pos= i;
                                  break;
                   return node.getChildAt(pos);
              public int getChildCount(Object parent)
                   DefaultMutableTreeNode node=
                        (DefaultMutableTreeNode) parent;
                   if (mShowStarBelliedSneeches)
                        return node.getChildCount();
                   int childCount= 0;
                   Enumeration children= node.children();
                   while (children.hasMoreElements()) {
                        if (((DefaultMutableTreeNode) children.nextElement()).getUserObject()
                                            instanceof PlainBelliedSneech)
                             childCount++;
                   return childCount;
              public boolean getShowStarBelliedSneeches() {
                   return mShowStarBelliedSneeches;
              public void setShowStarBelliedSneeches(boolean showStarBelliedSneeches)
                   if (showStarBelliedSneeches != mShowStarBelliedSneeches) {
                        mShowStarBelliedSneeches= showStarBelliedSneeches;
                        Object[] path= { mRoot };
                        int[] childIndices= new int[root.getChildCount()];
                        Object[] children= new Object[root.getChildCount()];
                        for (int i= 0; i< root.getChildCount(); i++) {
                             childIndices= i;
                             children[i]= root.getChildAt(i);
                        fireTreeStructureChanged(this, path, childIndices, children);
         private FilteredTree()
              final DefaultMutableTreeNode root= new DefaultMutableTreeNode("Root");
              DefaultMutableTreeNode parent;
              DefaultMutableTreeNode child;
              for (int i= 0; i< 2; i++) {
                   parent= new DefaultMutableTreeNode(new PlainBelliedSneech());
                   root.add(parent);
                   for (int j= 0; j< 2; j++) {
                        child= new DefaultMutableTreeNode(new StarBelliedSneech());
                        parent.add(child);
                        for (int k= 0; k< 2; k++)
                             child.add(new DefaultMutableTreeNode(new PlainBelliedSneech()));
                   for (int j= 0; j< 2; j++)
                        parent.add(new DefaultMutableTreeNode(new PlainBelliedSneech()));
                   parent= new DefaultMutableTreeNode(new StarBelliedSneech());
                   root.add(parent);
                   for (int j= 0; j< 2; j++) {
                        child= new DefaultMutableTreeNode(new PlainBelliedSneech());
                        parent.add(child);
                        for (int k= 0; k< 2; k++)
                             child.add(new DefaultMutableTreeNode(new StarBelliedSneech()));
                   for (int j= 0; j< 2; j++)
                        parent.add(new DefaultMutableTreeNode(new StarBelliedSneech()));
              final FilteredTreeModel model= new FilteredTreeModel(root);
              JTree tree= new JTree(model);
    tree.setShowsRootHandles(true);
    tree.putClientProperty("JTree.lineStyle", "Angled");
              tree.setRootVisible(false);
              JScrollPane sp= new JScrollPane(tree);
              sp.setPreferredSize(new Dimension(200,400));
              final JCheckBox check= new JCheckBox("Show Star Bellied Sneeches");
              check.setSelected(model.getShowStarBelliedSneeches());
              check.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent e) {
                        model.setShowStarBelliedSneeches(check.isSelected());
              JPanel panel= new JPanel(new BorderLayout());
              panel.add(check, BorderLayout.NORTH);
              panel.add(sp, BorderLayout.CENTER);
              JOptionPane.showOptionDialog(
                   null, panel, "Sneeches on Beeches",
                   JOptionPane.DEFAULT_OPTION,
                   JOptionPane.PLAIN_MESSAGE,
                   null, new String[0], null
              System.exit(0);
         public static void main(String[] argv) {
              new FilteredTree();

  • How to avoid the selection of a Parent node and its child node at a time?

    Example:
    consider the below JTree.
    Parent1
    ---->Parent2
    -------->Child3
    Parent3
    ---->Parent4
    My requirement :
    Parent1 and Parent3 can be selected at a time(using ctrl keys)
    Parent2 and Parent4 can be selected at a time
    Parent1 and Parent2 should not allowed to select at a time.
    In general : A parent and any of its child should not be selected at a time.
    How to achieve this? Anyone please help me.

    Thanikai wrote:
    I am very sorry.Whatever for? It's a valid question.
    How do i implement a custom TreeSelectionModel?I would start by going through the source of DefaultTreeSelectionModel so see how the default selection is handled. Also probably check out JTree.EmptySelectionModel to see how selection is prevented.
    Which methods to override?Methods in the class you choose to extend, obviously. But before that you need to firm up certain design decisions: if a parent node is selected and the user attempts to select one of its child nodes, do you select the child and deselect the parent or do nothing/ and vice versa.
    etc.... may form the basis for a future, more specific question accompanied by a [_SSCCE_|http://mindprod.com/jgloss/sscce.html].
    luck, db

Maybe you are looking for