Hide Tree Nodes
I've searched for some time, but have yet to find a solution
to this:
I wish to hide items ( html help item associated with each
node) in a tree with a xmlListCollection data provider . I found
this article:
http://www.axelscript.com/2008/02/20/using-a-data-manager-and-filtering-data-in-a-flex-tre e-even-the-nodes/
but I don't actually want to exclude the data from the
tree...just hide it...and access it to place the content elsewhere.
I've tried messing with the updateDisplayList function in my
custom treeItemRenderer, but I can't seem to completely hide the
presence of the list item
Thanks for any help!
Custom Data Descriptor:
http://livedocs.adobe.com/flex/3/html/help.html?content=about_dataproviders_6.html
Similar Messages
-
Useful Code of the Day: Hideable Tree Nodes
Someone posted about how they could selectively hide tree nodes, and I already had this AbstractTreeModel class (which does some things DefaultTreeModel does and some it doesn't) and a concrete subclass for TreeNode objects, so I was thinking how one could do hideable nodes. So I came up with this solution.
There's 4 classes here:
- AbstractTreeModel is the base for the concrete TreeNodeTreeModel
- TreeNodeTreeModel extends AbstractTreeModel to support TreeNodes (DefautlMutableTreeNode, etc.)
- HideableMutableTreeNode which is a DefautlMutableTreeNode subclass which has a visible field (with is/set methods, of course).
- HideableTreeModel is the hideable model which is a subclass of TreeNodeTreeModel.
A HideableMutableTreeNode can be set invisible directly, but the tree still needs to be notified to update. So it's best to use the methods in HideableTreeModel which set a node's visibility which notify the tree of changes accordingly. Methods are also provided to check a full path's visibility or ensure a node including all parent nodes are visible.
A HideableTreeModel can take any TreeNode class, it doesn't have to be all HideableMutableTreeNodes, but only HideableMutableTreeNodes can be made invisible, of course. Any other TreeNode type would just be considered visible.
Hiding nodes works basically by making the tree think there's less nodes then there are. And to do this, the node counts and child index search just works by looping thru the parent's children. This has potential perfomance drawbacks of course, since one has to loop thru the node's children to get nodes every time. This could be alleviated by not supporting non-hideable nodes changing the internal maintenance of HideableMutableTreeNode contents. But I'll leave that to whoever really needs it. It shouldn't be a problem if there are are a relatively small set of child nodes in any given parent.
Also, note that the root node in the model cannot be made invisible, cuz it'd be redundant since JTree can be set to hide the root node.
// *** HideableTreeModel ***
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
* <code>HideableTreeModel</code> is an <code>TreeNodeTreeModel</code>
* implementation for <code>HideableMutableTreeNode</code> objects. The
* model can also take any other <code>javax.swing.tree.TreeNode</code>
* objects.
public class HideableTreeModel extends TreeNodeTreeModel {
* Creates a new <code>HideableTreeModel</code> object.
* @param root the root node
public HideableTreeModel(TreeNode root) {
super(root);
* Checks if the specified node is visible. A node can only be
* hidden if the node is an instance of <code>HideableMutableTreeNode</code>. <br />
* <br />
* Note that this only test the visibility of the specified node, not
* whether a parent node is visible. Use <code>isPathToNodeVisible(Object)</code>
* to check if the full path is visible.
* @param node the node
* @param true if the node is visible, else false
public boolean isNodeVisible(Object node) {
if(node != getRoot()) {
if(node instanceof HideableMutableTreeNode) {
return ((HideableMutableTreeNode)node).isVisible();
return true;
* Sets the specified node to be hidden. A node can only be made hidden
* if the node is an instance of <code>HideableMutableTreeNode</code>. <br />
* <br />
* Note that this method will notify the tree to reflect any changes to
* node visibility. <br />
* <br />
* Note that this will not alter the visibility of any nodes in the
* specified node's path to the root node. Use
* <code>ensurePathToNodeVisible(Object)</code> instead to make sure the
* full path down to that node is visible. <br />
* <br />
* Note that this method will notify the tree to reflect any changes to
* node visibility.
* @param node the node
* @param v true for visible, false for hidden
* @param true if the node's visibility could actually change, else false
public boolean setNodeVisible(Object node, boolean v) {
// can't hide root
if(node != getRoot()) {
if(node instanceof HideableMutableTreeNode) {
HideableMutableTreeNode n = (HideableMutableTreeNode)node;
// don't fix what ain't broke...
if(v != n.isVisible()) {
TreeNode parent = n.getParent();
if(v) {
// need to get index after showing...
n.setVisible(v);
int index = getIndexOfChild(parent, n);
super.nodeInserted(parent, n, index);
} else {
// need to get index before hiding...
int index = getIndexOfChild(parent, n);
n.setVisible(v);
super.nodeRemoved(parent, n, index);
return true;
return false;
* Checks if the specified node is visible and all nodes above it are
* visible.
* @param node the node
* @param true if the path is visible, else false
public boolean isPathToNodeVisible(Object node) {
Object[] path = getPathToRoot(node);
for(int i = 0; i < path.length; i++) {
if(!isNodeVisible(path)) {
return false;
return true;
* Sets the specified node and all nodes above it to be visible.
* Note that this method will notify the tree to reflect any changes to
* node visibility.
* @param node the node
public void ensurePathToNodeVisible(Object node) {
Object[] path = getPathToRoot(node);
for(int i = 0; i < path.length; i++) {
setNodeVisible(path[i], true);
* Returns the child of parent at index index in the parent's child array.
* @param parent the parent node
* @param index the index
* @return the child or null if no children
public Object getChild(Object parent, int index) {
if(parent instanceof TreeNode) {
TreeNode p = (TreeNode)parent;
for(int i = 0, j = -1; i < p.getChildCount(); i++) {
TreeNode pc = (TreeNode)p.getChildAt(i);
if(isNodeVisible(pc)) {
j++;
if(j == index) {
return pc;
return null;
* Returns the number of children of parent.
* @param parent the parent node
* @return the child count
public int getChildCount(Object parent) {
int count = 0;
if(parent instanceof TreeNode) {
TreeNode p = (TreeNode)parent;
for(int i = 0; i < p.getChildCount(); i++) {
TreeNode pc = (TreeNode)p.getChildAt(i);
if(isNodeVisible(pc)) {
count++;
return count;
* Returns the index of child in parent.
* @param parent the parent node
* @param child the child node
* @return the index of the child node in the parent
public int getIndexOfChild(Object parent, Object child) {
int index = -1;
if(parent instanceof TreeNode && child instanceof TreeNode) {
TreeNode p = (TreeNode)parent;
TreeNode c = (TreeNode)child;
if(isNodeVisible(c)) {
index = 0;
for(int i = 0; i < p.getChildCount(); i++) {
TreeNode pc = (TreeNode)p.getChildAt(i);
if(pc.equals(c)) {
return index;
if(isNodeVisible(pc)) {
index++;
return index;
* Main method for testing.
* @param args the command-line arguments
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
HideableMutableTreeNode root = new HideableMutableTreeNode("root");
root.add(new HideableMutableTreeNode("child_1"));
final HideableMutableTreeNode c2 = new HideableMutableTreeNode("child_2");
c2.setVisible(false);
final HideableMutableTreeNode c2a = new HideableMutableTreeNode("child_2_A");
c2.add(c2a);
c2.add(new HideableMutableTreeNode("child_2_B"));
root.add(c2);
HideableMutableTreeNode c3 = new HideableMutableTreeNode("child_3");
HideableMutableTreeNode cC = new HideableMutableTreeNode("child_3_C");
cC.setVisible(false);
c3.add(cC);
c3.add(new HideableMutableTreeNode("child_3_D"));
root.add(c3);
root.add(new HideableMutableTreeNode("child_4"));
root.add(new HideableMutableTreeNode("child_5"));
DefaultMutableTreeNode c6 = new DefaultMutableTreeNode("child_6");
c6.add(new DefaultMutableTreeNode("child_6_A"));
c6.add(new DefaultMutableTreeNode("child_6_B"));
root.add(c6);
final HideableTreeModel model = new HideableTreeModel(root);
JTree tree = new JTree(model);
f.getContentPane().add(new JScrollPane(tree), BorderLayout.CENTER);
JButton b = new JButton("toggle");
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
model.setNodeVisible(c2, !model.isNodeVisible(c2));
//model.ensurePathToNodeVisible(c2a);
f.getContentPane().add(b, BorderLayout.SOUTH);
f.pack();
f.setSize(300, 500);
f.show();
// *** HideableMutableTreeNode ***
import javax.swing.*;
import javax.swing.tree.*;
* <code>HideableMutableTreeNode</code> is a <code>DefaultMutableTreeNode</code>
* implementation that works with <code>HideableTreeModel</code>.
public class HideableMutableTreeNode extends DefaultMutableTreeNode {
* The node is visible flag.
public boolean visible = true;
* Creates a tree node that has no parent and no children, but which
* allows children.
public HideableMutableTreeNode() {
super();
* Creates a tree node with no parent, no children, but which allows
* children, and initializes it with the specified user object.
* @param userObject - an Object provided by the user that
* constitutes the node's data
public HideableMutableTreeNode(Object userObject) {
super(userObject);
* Creates a tree node with no parent, no children, initialized with the
* specified user object, and that allows children only if specified.
* @param userObject - an Object provided by the user that
* constitutes the node's data
* @param allowsChildren - if true, the node is allowed to have child
* nodes -- otherwise, it is always a leaf node
public HideableMutableTreeNode(Object userObject, boolean allowsChildren) {
super(userObject, allowsChildren);
* Checks if the node is visible.
* @return true if the node is visible, else false
public boolean isVisible() {
return this.visible;
* Sets if the node is visible.
* @param v true if the node is visible, else false
public void setVisible(boolean v) {
this.visible = v;
// *** TreeNodeTreeModel ***
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
* <code>TreeNodeTreeModel</code> is an <code>AbstractTreeModel</code>
* implementation for <code>javax.swing.tree.TreeNode</code> objects.
public class TreeNodeTreeModel extends AbstractTreeModel {
* Creates a new <code>TreeNodeTreeModel</code> object.
* @param root the root node
public TreeNodeTreeModel(TreeNode root) {
super();
setRoot(root);
* Returns the parent of the child node.
* @param node the child node
* @return the parent or null if root
public Object getParent(Object node) {
if(node != getRoot() && (node instanceof TreeNode)) {
return ((TreeNode)node).getParent();
return null;
* Returns the child of parent at index index in the parent's child array.
* @param parent the parent node
* @param index the index
* @return the child or null if no children
public Object getChild(Object parent, int index) {
if(parent instanceof TreeNode) {
return ((TreeNode)parent).getChildAt(index);
return null;
* Returns the number of children of parent.
* @param parent the parent node
* @return the child count
public int getChildCount(Object parent) {
if(parent instanceof TreeNode) {
return ((TreeNode)parent).getChildCount();
return 0;
* Returns the index of child in parent.
* @param parent the parent node
* @param child the child node
* @return the index of the child node in the parent
public int getIndexOfChild(Object parent, Object child) {
if(parent instanceof TreeNode && child instanceof TreeNode) {
return ((TreeNode)parent).getIndex((TreeNode)child);
return -1;
* Returns true if node is a leaf.
* @param node the node
* @return true if the node is a leaf
public boolean isLeaf(Object node) {
if(node instanceof TreeNode) {
return ((TreeNode)node).isLeaf();
return true;
* Main method for testing.
* @param args the command-line arguments
public static void main(String[] args) {
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultMutableTreeNode root = new DefaultMutableTreeNode("root");
root.add(new DefaultMutableTreeNode("child_1"));
DefaultMutableTreeNode c2 = new DefaultMutableTreeNode("child_2");
c2.add(new DefaultMutableTreeNode("child_2_A"));
c2.add(new DefaultMutableTreeNode("child_2_B"));
root.add(c2);
root.add(new DefaultMutableTreeNode("child_3"));
root.add(new DefaultMutableTreeNode("child_4"));
JTree tree = new JTree(new TreeNodeTreeModel(root));
f.getContentPane().add(new JScrollPane(tree));
f.pack();
f.setSize(300, 500);
f.show();
// *** AbstractTreeModel ***
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
import java.text.*;
import java.util.*;
import javax.swing.*;
import javax.swing.event.*;
import javax.swing.tree.*;
public abstract class AbstractTreeModel implements TreeModel {
* The list of tree model listeners.
private Vector modelListeners = new Vector();
* The root object of the tree.
private Object root = null;
* Basic no-op constructor.
public AbstractTreeModel() {
* Gets the root object of the tree.
* @return the root object
public Object getRoot() {
return this.root;
* Sets the root object of the tree.
* @param r the root object
protected void setRoot(Object r) {
this.root = r;
* Gets the path to the root node for the specified object.
* @param node the root node
* @return the path to the object or <CODE>null</CODE>
public Object[] getPathToRoot(Object node) {
return getPathToRoot(node, 0);
* Gets the path to the root node for the specified object.
* @param node the root node
* @param i the current index
* @return the path to the object or <CODE>null</CODE>
private Object[] getPathToRoot(Object node, int i) {
Object anode[];
if(node == null) {
if(i == 0) {
return null;
anode = new Object[i];
} else {
i++;
if(node == getRoot()) {
anode = new Object[i];
} else {
anode = getPathToRoot(getParent(node), i);
anode[anode.length - i] = node;
return anode;
* Gets the parent object of the specified object. This method is not
* part of the <code>javax.swing.tree.TreeModel</code> interface, but is
* required to support the <code>getPathToRoot(Object)</code> method,
* which is widely used in this class. Therefore, it is important to
* correctly implement this method.
* @param obj the object
* @parma the parent object or null if no parent or invalid object
protected abstract Object getParent(Object obj);
* Adds a listener for the <CODE>TreeModelEvent</CODE> posted after the
* tree changes.
* @param l the tree model listener
public void addTreeModelListener(TreeModelListener l) {
modelListeners.addElement(l);
* Removes a listener previously added with addTreeModelListener().
* @param l the tree model listener
public void removeTreeModelListener(TreeModelListener l) {
modelListeners.removeElement(l);
* Forces the tree to reload. This is useful when many changes occur
* under the root node in the tree structure.
* <b>NOTE:</b> This will cause the tree to be collapsed. To maintain
* the expanded nodes, see the <code>getExpandedPaths(JTree)</code>
* and <code>expandPaths(JTree, ArrayList)</code> methods.
* @see #getExpandedPaths(JTree)
* @see #expandPaths(JTree, ArrayList)
public void reload() {
reload(getRoot());
* Forces the tree to repaint. This is useful when many changes occur
* under a specific node in the tree structure.
* <b>NOTE:</b> This will cause the tree to be collapsed below the
* updated node.
* @param node the node that changed
public void reload(Object node) {
if(node != null) {
TreePath tp = new TreePath(getPathToRoot(node));
fireTreeStructureChanged(new TreeModelEvent(this, tp));
* Messaged when the user has altered the value for the item identified
* by <CODE>path</CODE> to <CODE>newValue</CODE>.
* @param path the path to the changed object
* @param newValue the new value
public void valueForPathChanged(TreePath path, Object newValue) {
nodeChanged(path.getLastPathComponent());
* Notifies the tree that nodes were inserted. The index is looked up
* automatically.
* @param node the parent node
* @param child the inserted child node
public void nodeInserted(Object node, Object child) {
nodeInserted(node, child, -1);
* Notifies the tree that nodes were inserted.
* @param node the parent node
* @param child the inserted child node
* @param index the index of the child
public void nodeInserted(Object node, Object child, int index) {
if(index < 0) {
index = getIndexOfChild(node, child);
if(node != null && child != null && index >= 0) {
TreePath tp = new TreePath(getPathToRoot(node));
int[] ai = { index };
Object[] ac = { child };
fireTreeNodesInserted(new TreeModelEvent(this, tp, ai, ac));
* Notifies the tree that nodes were removed. The index is required
* since by this point, the object will no longer be in the tree.
* @param node the parent node
* @param child the removed child node
* @param index the index of the child
public void nodeRemoved(Object node, Object child, int index) {
if(node != null && child != null && index >= 0) {
TreePath tp = new TreePath(getPathToRoot(node));
int[] ai = { index };
Object[] ac = { child };
fireTreeNodesRemoved(new TreeModelEvent(this, tp, ai, ac));
* Notifies the tree that a node was changed.
* @param node the changed node
public void nodeChanged(Object node) {
if(node != null) {
TreePath tp = new TreePath(getPathToRoot(node));
fireTreeNodesChanged(new TreeModelEvent(this, tp, null, null));
* Fires "tree nodes changed" events to all listeners.
* @param event the tree model event
protected void fireTreeNodesChanged(TreeModelEvent event) {
for(int i = 0; i < modelListeners.size(); i++) {
((TreeModelListener)modelListeners.elementAt(i)).treeNodesChanged(event);
* Fires "tree nodes inserted" events to all listeners.
* @param event the tree model event
protected void fireTreeNodesInserted(TreeModelEvent event) {
for(int i = 0; i < modelListeners.size(); i++) {
((TreeModelListener)modelListeners.elementAt(i)).treeNodesInserted(event);
* Fires "tree nodes removed" events to all listeners.
* @param event the tree model event
protected void fireTreeNodesRemoved(TreeModelEvent event) {
for(int i = 0; i < modelListeners.size(); i++) {
((TreeModelListener)modelListeners.elementAt(i)).treeNodesRemoved(event);
* Fires "tree structure changed" events to all listeners.
* @param event the tree model event
protected void fireTreeStructureChanged(TreeModelEvent event) {
for(int i = 0; i < modelListeners.size(); i++) {
((TreeModelListener)modelListeners.elementAt(i)).treeStructureChanged(event);
* Records the list of currently expanded paths in the specified tree.
* This method is meant to be called before calling the
* <code>reload()</code> methods to allow the tree to store the paths.
* @param tree the tree
* @param pathlist the list of expanded paths
public ArrayList getExpandedPaths(JTree tree) {
ArrayList expandedPaths = new ArrayList();
addExpandedPaths(tree, tree.getPathForRow(0), expandedPaths);
return expandedPaths;
* Adds the expanded descendants of the specifed path in the specified
* tree to the internal expanded list.
* @param tree the tree
* @param path the path
* @param pathlist the list of expanded paths
private void addExpandedPaths(JTree tree, TreePath path, ArrayList pathlist) {
Enumeration enum = tree.getExpandedDescendants(path);
while(enum.hasMoreElements()) {
TreePath tp = (TreePath)enum.nextElement();
pathlist.add(tp);
addExpandedPaths(tree, tp, pathlist);
* Re-expands the expanded paths in the specified tree. This method is
* meant to be called before calling the <code>reload()</code> methods
* to allow the tree to store the paths.
* @param tree the tree
* @param pathlist the list of expanded paths
public void expandPaths(JTree tree, ArrayList pathlist) {
for(int i = 0; i < pathlist.size(); i++) {
tree.expandPath((TreePath)pathlist.get(i));Hey
I'm not trying to show anyone up here, but having just built a tree model for displaying an XML document in a tree, I thought this seemed like a neat exercise.
I implemented this very differently from the @OP. I only have one class, HiddenNodeTreeModel. All the hidden node data is stored in the model itself in my class. The advantage of what I've created is it will work with any TreeModel. The disadvantage is that I think it's not going to be very scalable - the additional computing to get the number of child nodes and to adjust indexes is heavy. So if you need a scalable solution definitely don't use this.
Anyway here you go
HiddenNodeTreeModel.java
======================
package tjacobs.ui.tree;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JTree;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;
import tjacobs.ui.WindowUtilities;
public class HiddenNodeTreeModel implements TreeModel {
TreeModel mModel;
ArrayList<Object> mHidden = new ArrayList<Object>();
public HiddenNodeTreeModel (TreeModel model) {
mModel = model;
public void addTreeModelListener(TreeModelListener arg0) {
mModel.addTreeModelListener(arg0);
private ArrayList<Integer> getHiddenChildren(Object parent) {
ArrayList<Integer> spots = new ArrayList<Integer>();
Iterator _i = mHidden.iterator();
while (_i.hasNext()) {
Object hidden = _i.next();
int idx = mModel.getIndexOfChild(parent, hidden);
if (idx != -1) {
spots.add(idx);
return spots;
public Object getChild(Object arg0, int index) {
ArrayList<Integer> spots = getHiddenChildren(arg0);
Collections.sort(spots);
Iterator<Integer> _i = spots.iterator();
while (_i.hasNext()) {
int num = _i.next();
if (num <= index) {
index++;
return mModel.getChild(arg0, index);
public int getChildCount(Object arg0) {
ArrayList list = getHiddenChildren(arg0);
System.out.println("size = " + list.size());
return mModel.getChildCount(arg0) - list.size();
public int getIndexOfChild(Object arg0, Object arg1) {
int index = mModel.getIndexOfChild(arg0, arg1);
ArrayList<Integer> spots = getHiddenChildren(arg0);
Collections.sort(spots);
Iterator<Integer> _i = spots.iterator();
int toSub = 0;
while (_i.hasNext()) {
int num = _i.next();
if (num <= index) {
toSub++;
return index - toSub;
public Object getRoot() {
// TODO Auto-generated method stub
return mModel.getRoot();
public boolean isLeaf(Object arg0) {
// TODO Auto-generated method stub
return mModel.isLeaf(arg0);
public void removeTreeModelListener(TreeModelListener arg0) {
mModel.removeTreeModelListener(arg0);
public void valueForPathChanged(TreePath arg0, Object arg1) {
mModel.valueForPathChanged(arg0, arg1);
public void hideNode(Object node) {
if (node instanceof TreePath) {
node = ((TreePath)node).getLastPathComponent();
mHidden.add(node);
public void showNode(Object node) {
mHidden.remove(node);
public void showAll() {
mHidden.clear();
* @param args
public static void main(String[] args) {
// TODO Auto-generated method stub
DefaultMutableTreeNode A = new DefaultMutableTreeNode("A");
DefaultMutableTreeNode B = new DefaultMutableTreeNode("B");
DefaultMutableTreeNode C = new DefaultMutableTreeNode("C");
DefaultMutableTreeNode D = new DefaultMutableTreeNode("D");
DefaultMutableTreeNode E = new DefaultMutableTreeNode("E");
DefaultMutableTreeNode F = new DefaultMutableTreeNode("F");
A.add(B);
B.add(C);
B.add(D);
B.add(E);
E.add(F);
DefaultTreeModel model = new DefaultTreeModel(A);
final HiddenNodeTreeModel hmodel = new HiddenNodeTreeModel(model);
final JTree tree = new JTree(hmodel);
JFrame jf = new JFrame("HiddenNodeTreeModel Test");
jf.add(tree);
JMenuBar bar = new JMenuBar();
jf.setJMenuBar(bar);
JMenu menu = new JMenu("Options");
bar.add(menu);
final JMenuItem hide = new JMenuItem("Hide");
final JMenuItem show = new JMenuItem("ShowAll");
menu.add(hide);
menu.add(show);
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == hide) {
hmodel.hideNode(tree.getSelectionPath());
tree.updateUI();
else {
hmodel.showAll();
tree.updateUI();
hide.addActionListener(al);
show.addActionListener(al);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setBounds(100,100,100,100);
jf.setVisible(true);
} -
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,
SwathiAE Basics
Keyframe the mask path. -
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.
LindaHere'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 hide the default arrow icon of af:tree node
Hi All,
I am using Oracle JDeveloper 11g R2.
I want to hide the arrow icon which is displayed by default with af:tree node. The use case is to display custom icons for all the nodes. The problem is that when I am customizing icons of tree node, it is showing arrow as well as the icon with each node. Which doesn't seems fine. Can any one help/guide on how to hide the default af:tree node arrow icon.
Thanks in advance.
Regards
Bilal
Edited by: Bilal on 29-May-2012 01:32Hi,
Use Css to change the icon style:
af|treeTable::expanded-icon {
content: url("/adf/1.gif");//content : none;
outline: none ;
af|treeTable::collapsed-icon {
content: url("/adf/2.gif");//content : none;
outline: none ;
af|treeTable::leaf-icon {
content: url("/adf/3.gif");//content : none;
outline: none ;
Regards,
Raj Gopal K -
Dear all.
How can i open new FORM, when i double click at (tree) node.
Best Regards
node
|__node1
|__node11 <-- double click and open new FORM
|__node12
|__node2
|__node21
Message was edited by:
First_StepWhe-tree-node-activated trigger
declare
pl_id paramlist;
value1 varchar2(100) ;
begin
-- Checks whether the trigger node is a leaf not or not if yes
-- Call the Corresponding form else do nothing
if (Ftree.Get_Tree_Node_Property('tree_block.tree1', :SYSTEM.TRIGGER_NODE, Ftree.NODE_STATE)= 0) THEN
--CREATE PARAM LIST FOR CALL_FORM
pl_id:=get_parameter_list('userparam');
if(id_null(pl_id)) then
pl_id:=create_parameter_list('userparam');
else
destroy_parameter_list(pl_id);
pl_id:=create_parameter_list('userparam');
end if;
--ADD NEEDED PARAMETERS
add_parameter(pl_id,'user_name',text_parameter,:parameter.user_name);
--HERE NODE VALUE IS FORM NAME
value1:=Ftree.get_tree_node_property('tree_block.tree1', :system.trigger_node,ftree.node_value);
call_form(value1,hide,no_replace,no_query_only,pl_id);
END IF;
end;
jeneesh -
Add/Edit/Delete Tree Nodes using CL_GUI_ALV_TREE
Hi All,
I am looking for an example of program with CL_GUI_ALV_TREE that have a functionality of add a tree node, edit a tree node, and delete a tree node.
I have already looked the BCALV_TREE* demo program but could not able to find a program to add/edit/delete node tree elements.
Any info on this.
Thanks
aRsHello aRs
Here is a sample report showing how to delete nodes in an ALV tree. The report was copied from BCALV_TREE_01. Search for added code:
*$ADDED: begin
*$ADDED: end[/code]
When you display the tree expand the first folder completely. When entering 'DELETE' into the command field directly the first flight date node will be deleted.
REPORT ZUS_SDN_BCALV_TREE_01_DELNODE.
based on: REPORT bcalv_tree_01.
Purpose:
~~~~~~~~
This report shows the essential steps to build up a hierarchy
using an ALV Tree Control (class CL_GUI_ALV_TREE).
Note that it is not possible to build up this hierarchy
using a simple ALV Tree Control (class CL_GUI_ALV_TREE_SIMPLE).
To check program behavior
~~~~~~~~~~~~~~~~~~~~~~~~~
Start this report. The hierarchy tree consists of nodes for each
month on top level (this level can not be build by a simple ALV Tree
because there is no field for months in our output table SFLIGHT.
Thus, you can not define this hierarchy by sorting).
Nor initial calculations neither a special layout has been applied
(the lines on the right do not show anything).
Note also that this example does not build up and change the
fieldcatalog of the output table. For this reason, all fields
of the output table are shown in the columns although the fields
CARRID and FLDATE are already placed in the tree on the left.
(Of course, this is not a good style. See BCALV_TREE_02 on how to
hide columns).
Essential steps (Search for '§')
~~~~~~~~~~~~~~~
1.Usual steps when using control technology.
1a. Define reference variables.
1b. Create ALV Tree Control and corresponding container.
2.Create Hierarchy-header
3.Create empty Tree Control
4.Create hierarchy (nodes and leaves)
4a. Select data
4b. Sort output table according to your conceived hierarchy
4c. Add data to tree
5.Send data to frontend.
6.Call dispatch to process toolbar functions
*$ADDED: begin
DATA:
gd_del_nkey TYPE lvc_nkey.
*$ADDED: end
§1a. Define reference variables
DATA: g_alv_tree TYPE REF TO cl_gui_alv_tree,
g_custom_container TYPE REF TO cl_gui_custom_container.
DATA: gt_sflight TYPE sflight OCCURS 0, "Output-Table
ok_code LIKE sy-ucomm,
save_ok LIKE sy-ucomm, "OK-Code
g_max TYPE i VALUE 255.
END-OF-SELECTION.
CALL SCREEN 100.
*& Module PBO OUTPUT
process before output
MODULE pbo OUTPUT.
SET PF-STATUS 'MAIN100'.
SET TITLEBAR 'MAINTITLE'.
IF g_alv_tree IS INITIAL.
PERFORM init_tree.
CALL METHOD cl_gui_cfw=>flush
EXCEPTIONS
cntl_system_error = 1
cntl_error = 2.
IF sy-subrc NE 0.
CALL FUNCTION 'POPUP_TO_INFORM'
EXPORTING
titel = 'Automation Queue failure'(801)
txt1 = 'Internal error:'(802)
txt2 = 'A method in the automation queue'(803)
txt3 = 'caused a failure.'(804).
ENDIF.
ENDIF.
ENDMODULE. " PBO OUTPUT
*& Module PAI INPUT
process after input
MODULE pai INPUT.
save_ok = ok_code.
CLEAR ok_code.
CASE save_ok.
WHEN 'EXIT' OR 'BACK' OR 'CANC'.
PERFORM exit_program.
*$ADDED: begin
WHEN 'DELETE'.
CALL METHOD g_alv_tree->delete_subtree
EXPORTING
i_node_key = gd_del_nkey
I_UPDATE_PARENTS_EXPANDER = SPACE
i_update_parents_folder = 'X'
EXCEPTIONS
node_key_not_in_model = 1
OTHERS = 2.
IF sy-subrc <> 0.
MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
ENDIF.
CALL METHOD g_alv_tree->frontend_update.
*$ADDED: end
WHEN OTHERS.
§6. Call dispatch to process toolbar functions
CALL METHOD cl_gui_cfw=>dispatch.
ENDCASE.
CALL METHOD cl_gui_cfw=>flush.
ENDMODULE. " PAI INPUT
*& Form init_tree
text
--> p1 text
<-- p2 text
FORM init_tree.
§1b. Create ALV Tree Control and corresponding Container.
create container for alv-tree
DATA: l_tree_container_name(30) TYPE c.
l_tree_container_name = 'CCONTAINER1'.
CREATE OBJECT g_custom_container
EXPORTING
container_name = l_tree_container_name
EXCEPTIONS
cntl_error = 1
cntl_system_error = 2
create_error = 3
lifetime_error = 4
lifetime_dynpro_dynpro_link = 5.
IF sy-subrc <> 0.
MESSAGE x208(00) WITH 'ERROR'(100).
ENDIF.
create tree control
CREATE OBJECT g_alv_tree
EXPORTING
parent = g_custom_container
node_selection_mode = cl_gui_column_tree=>node_sel_mode_single
item_selection = 'X'
no_html_header = 'X'
no_toolbar = ''
EXCEPTIONS
cntl_error = 1
cntl_system_error = 2
create_error = 3
lifetime_error = 4
illegal_node_selection_mode = 5
failed = 6
illegal_column_name = 7.
IF sy-subrc <> 0.
MESSAGE x208(00) WITH 'ERROR'. "#EC NOTEXT
ENDIF.
§2. Create Hierarchy-header
The simple ALV Tree uses the text of the fields which were used
for sorting to define this header. When you use
the 'normal' ALV Tree the hierarchy is build up freely
by the programmer this is not possible, so he has to define it
himself.
DATA l_hierarchy_header TYPE treev_hhdr.
PERFORM build_hierarchy_header CHANGING l_hierarchy_header.
§3. Create empty Tree Control
IMPORTANT: Table 'gt_sflight' must be empty. Do not change this table
(even after this method call). You can change data of your table
by calling methods of CL_GUI_ALV_TREE.
Furthermore, the output table 'gt_outtab' must be global and can
only be used for one ALV Tree Control.
CALL METHOD g_alv_tree->set_table_for_first_display
EXPORTING
i_structure_name = 'SFLIGHT'
is_hierarchy_header = l_hierarchy_header
CHANGING
it_outtab = gt_sflight. "table must be empty !
§4. Create hierarchy (nodes and leaves)
PERFORM create_hierarchy.
§5. Send data to frontend.
CALL METHOD g_alv_tree->frontend_update.
wait for automatic flush at end of pbo
ENDFORM. " init_tree
*& Form build_hierarchy_header
build hierarchy-header-information
-->P_L_HIERARCHY_HEADER strucxture for hierarchy-header
FORM build_hierarchy_header CHANGING
p_hierarchy_header TYPE treev_hhdr.
p_hierarchy_header-heading = 'Month/Carrier/Date'(300).
p_hierarchy_header-tooltip = 'Flights in a month'(400).
p_hierarchy_header-width = 30.
p_hierarchy_header-width_pix = ' '.
ENDFORM. " build_hierarchy_header
*& Form exit_program
free object and leave program
FORM exit_program.
CALL METHOD g_custom_container->free.
LEAVE PROGRAM.
ENDFORM. " exit_program
*& Form create_hierarchy
text
--> p1 text
<-- p2 text
FORM create_hierarchy.
DATA: ls_sflight TYPE sflight,
lt_sflight TYPE sflight OCCURS 0,
l_yyyymm(6) TYPE c, "year and month of sflight-fldate
l_yyyymm_last(6) TYPE c,
l_carrid LIKE sflight-carrid,
l_carrid_last LIKE sflight-carrid.
DATA: l_month_key TYPE lvc_nkey,
l_carrid_key TYPE lvc_nkey,
l_last_key TYPE lvc_nkey.
§4a. Select data
SELECT * FROM sflight INTO TABLE lt_sflight UP TO g_max ROWS.
§4b. Sort output table according to your conceived hierarchy
We sort in this order:
year and month (top level nodes, yyyymm of DATS)
carrier id (next level)
day of month (leaves, dd of DATS)
SORT lt_sflight BY fldate0(6) carrid fldate6(2).
Note: The top level nodes do not correspond to a field of the
output table. Instead we use data of the table to invent another
hierarchy level above the levels that can be build by sorting.
§4c. Add data to tree
LOOP AT lt_sflight INTO ls_sflight.
Prerequesite: The table is sorted.
You add a node everytime the values of a sorted field changes.
Finally, the complete line is added as a leaf below the last
node.
l_yyyymm = ls_sflight-fldate+0(6).
l_carrid = ls_sflight-carrid.
Top level nodes:
IF l_yyyymm <> l_yyyymm_last. "on change of l_yyyymm
l_yyyymm_last = l_yyyymm.
*Providing no key means that the node is added on top level:
PERFORM add_month USING l_yyyymm
CHANGING l_month_key.
The month changed, thus, there is no predecessor carrier
CLEAR l_carrid_last.
ENDIF.
Carrier nodes:
(always inserted as child of the last month
which is identified by 'l_month_key')
IF l_carrid <> l_carrid_last. "on change of l_carrid
l_carrid_last = l_carrid.
PERFORM add_carrid_line USING ls_sflight
l_month_key
CHANGING l_carrid_key.
ENDIF.
Leaf:
(always inserted as child of the last carrier
which is identified by 'l_carrid_key')
PERFORM add_complete_line USING ls_sflight
l_carrid_key
CHANGING l_last_key.
ENDLOOP.
ENDFORM. " create_hierarchy
*& Form add_month
FORM add_month USING p_yyyymm TYPE c
p_relat_key TYPE lvc_nkey
CHANGING p_node_key TYPE lvc_nkey.
DATA: l_node_text TYPE lvc_value,
ls_sflight TYPE sflight,
l_month(15) TYPE c. "output string for month
get month name for node text
PERFORM get_month USING p_yyyymm
CHANGING l_month.
l_node_text = l_month.
add node:
ALV Tree firstly inserts this node as a leaf if you do not provide
IS_NODE_LAYOUT with field ISFOLDER set. In form 'add_carrid_line'
the leaf gets a child and thus ALV converts it to a folder
automatically.
CALL METHOD g_alv_tree->add_node
EXPORTING
i_relat_node_key = p_relat_key
i_relationship = cl_gui_column_tree=>relat_last_child
i_node_text = l_node_text
is_outtab_line = ls_sflight
IMPORTING
e_new_node_key = p_node_key.
ENDFORM. " add_month
FORM add_carrid_line USING ps_sflight TYPE sflight
p_relat_key TYPE lvc_nkey
CHANGING p_node_key TYPE lvc_nkey.
DATA: l_node_text TYPE lvc_value,
ls_sflight TYPE sflight.
add node
ALV Tree firstly inserts this node as a leaf if you do not provide
IS_NODE_LAYOUT with field ISFOLDER set. In form 'add_carrid_line'
the leaf gets a child and thus ALV converts it to a folder
automatically.
l_node_text = ps_sflight-carrid.
CALL METHOD g_alv_tree->add_node
EXPORTING
i_relat_node_key = p_relat_key
i_relationship = cl_gui_column_tree=>relat_last_child
i_node_text = l_node_text
is_outtab_line = ls_sflight
IMPORTING
e_new_node_key = p_node_key.
ENDFORM. " add_carrid_line
*& Form add_complete_line
FORM add_complete_line USING ps_sflight TYPE sflight
p_relat_key TYPE lvc_nkey
CHANGING p_node_key TYPE lvc_nkey.
DATA: l_node_text TYPE lvc_value.
WRITE ps_sflight-fldate TO l_node_text MM/DD/YYYY.
add leaf:
ALV Tree firstly inserts this node as a leaf if you do not provide
IS_NODE_LAYOUT with field ISFOLDER set.
Since these nodes will never get children they stay leaves
(as intended).
CALL METHOD g_alv_tree->add_node
EXPORTING
i_relat_node_key = p_relat_key
i_relationship = cl_gui_column_tree=>relat_last_child
is_outtab_line = ps_sflight
i_node_text = l_node_text
IMPORTING
e_new_node_key = p_node_key.
*$ADDED: begin
IF ( ps_sflight-fldate = '20040522' ). " first flight date
IF ( gd_del_nkey IS INITIAL ). " collect only first date
gd_del_nkey = p_node_key.
ENDIF.
ENDIF.
*$ADDED: end
ENDFORM. " add_complete_line
*& Form GET_MONTH
text
-->P_P_YYYYMM text
<--P_L_MONTH text
FORM get_month USING p_yyyymm
CHANGING p_month.
Returns the name of month according to the digits in p_yyyymm
DATA: l_monthdigits(2) TYPE c.
l_monthdigits = p_yyyymm+4(2).
CASE l_monthdigits.
WHEN '01'.
p_month = 'January'(701).
WHEN '02'.
p_month = 'February'(702).
WHEN '03'.
p_month = 'March'(703).
WHEN '04'.
p_month = 'April'(704).
WHEN '05'.
p_month = 'May'(705).
WHEN '06'.
p_month = 'June'(706).
WHEN '07'.
p_month = 'July'(707).
WHEN '08'.
p_month = 'August'(708).
WHEN '09'.
p_month = 'September'(709).
WHEN '10'.
p_month = 'October'(710).
WHEN '11'.
p_month = 'November'(711).
WHEN '12'.
p_month = 'December'(712).
ENDCASE.
CONCATENATE p_yyyymm+0(4) '->' p_month INTO p_month.
ENDFORM. " GET_MONTH
/code
Regards
Uwe -
Hiding Page 0 Items and Tree Node Links
I have two issues I'm trying to work out:
1) I have created a tree on page 0 that I want to appear on all of my REPORT pages, so the user can filter the reports regardless of which page they're on. The problem is that the tree is also appearing on the login page and the Home page. Is there any way to hide the tree on the login and home pages but have it appear on all other pages? I'm trying to avoid having to create the tree on every single report page.
2) I need the tree to work like this: the user clicks any node in the tree, and all reports (on multiple pages) are filtered based on the node selected. So I don't actually want the nodes to be links to a report, I just want the reports to be filtered based on the node value selected. Then I'll have tabs to navigate between the different reports. Is this possible?
Thanks.I dunno if you correct it, but there was small mistake in the JS code - a closing bracket was missing
$s('P0_TREE_NODE', $(this.triggeringElement).parents('li:first').attr('id'));
it looks like the node value IS being stored in the session stateI hope you checked for items in page 0 (it should then list down page 0 items including P0_TREE_NODE) when you searched for session state(it defaults to whichever page is run currently)
If these two are working fine, it has to be some page process/computation/item source/item default that modifies the item value when you move between pages.
To find this: Turn debug on, reload the page , click on a tree node, then redirect to some other page and then check the debug report and see if the page 0 item: P0_TREE_NODE is being set/reset/modified elsewhere. -
Hide leaf nodes from jtree.
Hi,
How can I hide all nodes that are leafs on a tree? Basically, I'm creating a splitpane where on the left side I have a jtree where when a user clicks on a node on that jtree the leaf nodes will appear on the right split pane as icons.
VThanks for the reply...
I wanted to include the leaf nodes in the tree model so that I won't need to work with two data structures--one with the leaf nodes, and another without the leaf nodes.
So far, I think I resolved the problem. I created my own treemodel class where I pass a defaulttreemodel into it and created a modified getChildCount which will go into the defaulttreemodel and filter out the leaf nodes.
It all seems to work pretty well.
My problem now... How do I remove the stupid node icons? :)
I just want the dashed lines to appear and nothing more....
Thanks again...
V -
Hi All
I have a JTree, and would like to hide some tree nodes based on a certain path, i have been using the setFilter and I can't seem to get to work.
Regards
M
Code fragment below: using the FilterTreeModel
void cmdShowSubset_actionPerformed(ActionEvent e) {
DefaultMutableTreeNode tn = new DefaultMutableTreeNode(value);
FilterTreeModel ftm = new FilterTreeModel(tn);
ftm.setFilterNode(tn);
Object[] oArray = new Object[1];
oArray[0]="ABC communications";
tp = new TreePath(oArray);
subTree.setSelectionPath(tp);
class FilterTreeModel
extends javax.swing.tree.DefaultTreeModel {
DefaultMutableTreeNode filterNode;
public FilterTreeModel(DefaultMutableTreeNode root) {
super(root);
public int getChildCount(Object obj) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) obj;
if (filterNode != null && !filterNode.isNodeDescendant(node)) {
if (node.isNodeDescendant(filterNode))
return 1;
return 0;
return super.getChildCount(node);
public Object getChild(Object obj, int num) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) obj;
if (filterNode != null && !filterNode.isNodeDescendant(node)) {
if (node.isNodeDescendant(filterNode)) {
TreeNode temp = filterNode;
while (!node.isNodeChild(temp)) {
temp = temp.getParent();
return temp;
return null;
return super.getChild(node, num);
public void setFilterNode(DefaultMutableTreeNode node) {
filterNode = node;
DefaultMutableTreeNode root = (DefaultMutableTreeNode)super.getRoot();
super.fireTreeStructureChanged(root, super.getPathToRoot(root), null, null);When you post code, please use [code] and [/code] tags as described in Formatting Help on the message entry page. It makes it much easier to read.
-
How to resize a custom tree node like you would a JFrame window?
Hello,
I am trying to resize a custom tree node like you would a JFrame window.
As with a JFrame, when your mouse crosses the Border, the cursor should change and you are able to drag the edge to resize the node.
However, I am faced with a problem. Border cannot detect this and I dont want to use a mouse motion listener (with a large number of nodes, I fear it will be inefficient, calculating every node's position constantly).
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Insets;
import java.util.EventObject;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellEditor;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeSelectionModel;
public class ResizeNode extends JPanel {
AnilTreeCellRenderer2 atcr;
AnilTreeCellEditor2 atce;
DefaultTreeModel treeModel;
JTree tree;
DefaultMutableTreeNode markedNode = null;
public ResizeNode() {
super(new BorderLayout());
treeModel = new DefaultTreeModel(null);
tree = new JTree(treeModel);
tree.setEditable(true);
tree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.setShowsRootHandles(true);
tree.setCellRenderer(atcr = new AnilTreeCellRenderer2());
tree.setCellEditor(atce = new AnilTreeCellEditor2(tree, atcr));
JScrollPane scrollPane = new JScrollPane(tree);
add(scrollPane,BorderLayout.CENTER);
public void setRootNode(DefaultMutableTreeNode node) {
treeModel.setRoot(node);
treeModel.reload();
public static void main(String[] args){
ResizeNode tb = new ResizeNode();
tb.setPreferredSize(new Dimension(400,200));
JFrame frame = new JFrame("ResizeNode");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setContentPane(tb);
frame.setSize(400, 200);
frame.pack();
frame.setVisible(true);
tb.populate();
private void populate() {
TextAreaNode2 r = new TextAreaNode2(this);
setRootNode(r);
TextAreaNode2 a = new TextAreaNode2(this);
treeModel.insertNodeInto(a, r, r.getChildCount());
class AnilTreeCellRenderer2 extends DefaultTreeCellRenderer{
TreeBasic panel;
DefaultMutableTreeNode currentNode;
public AnilTreeCellRenderer2() {
super();
public Component getTreeCellRendererComponent
(JTree tree, Object value, boolean selected, boolean expanded,
boolean leaf, int row, boolean hasFocus){
TextAreaNode2 currentNode = (TextAreaNode2)value;
NodeGUI2 gNode = (NodeGUI2) currentNode.gNode;
return gNode.box;
class AnilTreeCellEditor2 extends DefaultTreeCellEditor{
DefaultTreeCellRenderer rend;
public AnilTreeCellEditor2(JTree tree, DefaultTreeCellRenderer r){
super(tree, r);
rend = r;
public Component getTreeCellEditorComponent(JTree tree, Object value,
boolean isSelected, boolean expanded, boolean leaf, int row){
return rend.getTreeCellRendererComponent(tree, value, isSelected, expanded,
leaf, row, true);
public boolean isCellEditable(EventObject event){
return true;
class NodeGUI2 {
final ResizeNode view;
Box box = Box.createVerticalBox();
final JTextArea aa = new JTextArea( 1, 5 );
final JTextArea aaa = new JTextArea( 1, 8 );
NodeGUI2( ResizeNode view_ ) {
this.view = view_;
box.add( aa );
aa.setBorder( BorderFactory.createMatteBorder( 0, 0, 1, 0, Color.GREEN ) );
box.add( aaa );
box.setBorder( BorderFactory.createMatteBorder( 5, 5, 5, 5, Color.CYAN ) );
private Dimension getEditorPreferredSize() {
Insets insets = box.getInsets();
Dimension boxSize = box.getPreferredSize();
Dimension aaSize = aa.getPreferredSize();
Dimension aaaSize = aaa.getPreferredSize();
int height = aaSize.height + aaaSize.height + insets.top + insets.bottom;
int width = Math.max( aaSize.width, aaaSize.width );
if ( width < boxSize.width )
width += insets.right + insets.left + 3; // 3 for cursor
return new Dimension( width, height );
class TextAreaNode2 extends DefaultMutableTreeNode {
NodeGUI2 gNode;
TextAreaNode2(ResizeNode view_) {
gNode = new NodeGUI2(view_);
}the node on the tree is only painted on using the
renderer to do the painting work. A mouse listener
has to be added to the tree, and when moved over an
area, you have to determine if you are over the
border and which direction to update the cursor and
to know which way to resize when dragged. One of the
BasicRootPaneUI has some code that can help determine
that.Thanks for replying. What is your opinion on this alternative idea that I just had?
I am wondering if it might be easier to have a toggle button in the node that you click when you want to resize the node. Then a mouse-down and dragging the mouse will resize the node. Mouse-up will reset the toggle button, and so will mouse down in an invalid area.
Anil -
Tree item when-tree-node-selected fires differently from 6i to 10g.
In forms 6i, when you keyboard navigate between tree nodes, the wtns trigger will fire. In 10g it does not. In 10g, it will fire if you press the tab key or mouse click on a node.
Anyone know if this was done on purpose?
I ran into this after finally trying my props.fmb in 10g. It works fine in 6i, but not in 10g
copy of my form is here:
http://www.tailboom.com/oracle.php
Forms [32 Bit] Version 6.0.8.18.3 (Production) cleint server
Forms [32 Bit] Version 10.1.2.0.2 (Production)
I wrote most of the tree handling code for oracle apps APPTREE. This is the code that most if not all tree's in apps uses to build standard tree. So I have a pretty good understanding of the forms tree item. And know the wtns fired for web forms 6i on every node like 6i client server. This is very strange IMO.
Thanks.
--patOleg,
thanks for the reference. Although the bug you identify deals with when-tree-node-activated, it is possible they fixed the when-tree-node-selected issue at the same time. With my test tree, i can currently duplicate both issues. I tried to download the patch, but it is only available for linux and unix. No windows patch. I don't have my linux env up and running to where I can test yet. So I can not confirm.
--pat -
How to get a Tree Node Value when a Tree is Expanded
My reqiurement is when i Expand a Tree i need the Expanded tree Node Value. For Example Consider Parent as a Root Node of a Tree, and Consider its two Children Child1 and Child2.
When + Parent Expanded
I will Get the Output as --Parent
- Child1
- Child2
so As when i expand the Tree i must Get the String Value Parent.duplicate
How to get a Tree Node Value when a Tree is Expanded -
Assigning Selected Tree Node Value To An Item
Hi guys,
I want to assign selected tree node's value to a page item. This item can be a textbox or a label (display only). How can i do that? I tried to use "Selected Node Page Item" property which is available on Tree Attributes. But I couldn't assign the value without refreshing whole page.
Do you have any idea?
Thanks.Hi ,
Thank you that was exactly what I was looking for. I couldn't find how to pass database column to javascript as an input parameter. So thanks for your help. I made a couple of correction :
1) I put additional ' characters to ('''||"NAME"||''') this part because my field is varchar.
select case when connect_by_isleaf = 1 then 0
when level = 1 then 1
else -1
end as status,
level,
NAME as title,
null as icon,
"ID" as value,
null as tooltip,
'javascript:setFObjName('''||"NAME"||''')' As link
from "#OWNER#"."TABLE_NAME"
start with "PID" is null
connect by prior "ID" = "PID"
2) In script I have added ' character before and after page item.
function setFObjName(pobjName){
$s('P1_OBJ_NAME', pobjName);
So it works. Thanks tfor your help. -
Problems in creating a preorder tree node arraylist
Hi, i want to create an arraylist containing a preorder tree node's name, the program compiled well but every time it gives error when i press the "Output Preorder" button to create the arraylist, the following is the code, can someone help? Thanks a lot!!
JButton outputPreorderButton = new JButton("Output Preorder");
outputPreorderButton.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent e)
for (Enumeration evev = tableTreeRootNode.preorderEnumeration() ; evev.hasMoreElements() ;) {
System.out.println(evev.nextElement());
String s = (String)evev.nextElement();
tableTreeNodesArray.add(s);Yeah, well, it will "give error" (as you so precisely and informatively say) if there's an odd number of nodes in your tree. Consider your code:System.out.println(evev.nextElement());
// Get element number 1 and print it.
String s = (String)evev.nextElement();
tableTreeNodesArray.add(s);
// Get element number 2 and add it to the list.So, the odd-numbered elements you print. The even-numbered elements you add to the list. If it happens there are 31 nodes, then an error will occur when you try to get node 32.
Maybe you are looking for
-
How do you MAKE Pages save so you don't have to lose stuff?
Pages isn't always saving in Lion. If you close a Pages document and return to it later, things are not always saved. Is there a trick to Save like back in the days?
-
i tunes not working and the problem its displaying is m signature: Problem Event Name: BEX Application Name: iTunes.exe Application Version: 10.5.3.3 Application Timestamp: 4f14cc3d Fault Module Name: QuickTime.qts_unloaded
-
After upgrading my iMac to Mavericks, Adobe InDesign cs5 crashes when I try to load it. I uninstalled and reinstalled from the disk. Now I get an "Error: 5" message and it still doesn't load. How can I fix this? crossink
-
Video plays fine in iTunes / only plays audio in iPod
I put an MPG4 movie into iTunes and it plays fine in iTunes. After syncing it into my iPod, I find that it plays the sound but not the actual video and it shows a tiny still of the video where the album cover usually goes. Please help.
-
Accessing String variables from several JAVA classes
Hi. I have several java classes that accesses the same String variables. Instead of putting the String declarations in every java files, how can I put these declarations in a single file source, and get each java class to get the variables data from