Tree node expansion
Hello
I have a tree (showing max levels of 2)and I am trying to programatically open a particular node that is 3 levels down.
Now, I can open a node that is 2 levels down as follows
https://...../f?p=1056:2:3052972033689458:EXPAND,9::::#node10
So,parent node'9' is opened and I can view child node 10.
However, I want to expand child node 10 too simultaneously , so that I can view its child '11'.
In other words, I want to open the tree node pragramatically as many levels as needed to display the desired child node.
Is there any way I can do that. Thanks.
Suni
Edited by: suni1 on May 24, 2010 12:16 PM
I have got the answer.I am having trouble reading your mind. Could you please use more power when transmitting the code that demonstrates the problem. Make sure you transmit the full stack trace of any exception.
Similar Messages
-
Tree node Expansion programmatically?
How can i expand a node(which has sub nodes)
on Tree programmatically?Hi Ali
Have a look at JTree.expandrow()
Marc -
Hi,
I have got a JTree with various nodes and subnodes.
If a parent node has got subnodes, you can see a little box with a '+' in it.
now,
1. Click on the parent node '+' box and the node expands to show the sub nodes.
2. Double click on the parent node itself and it also expands.
I want to eliminate the behaviour of number 2.
This is because I want to use the double click on the parent node to do something else.
Can anyone help?
Cheers,
JimIn jdk1.3 or higher:
tree.setToggleClickCount(-1); -
Need coordinate for particular tree node as currently expanded
Hi All,
i am working in flex for the past two months,currently i am
working on the drag and drop on a tree , where i am able to drag
one tree leaf node to another another tree leaf node and i am able
to draw a line between the two leaf node indicating that this has
been dragged from the previous tree of a particular node to the
current node of the tree.
The problem which i am facing is that when i collapse the
expanded tree , the line which i have drawn is not able to
synchronize with the tree expand or collapse (the line remains in
the same position even when the particular leaf node move down coz
of expansion of the above tree node.)
any help will be appreciated.there is a private function in the tree.as class:
private function getVisibleChildrenCount(item:Object):int
that I can use by multiplying how many children there are by
how tall each item "physically" displays on the screen as, but I
want to get that publicly. I don't want to go about hacking the
tree.as code, that's poor form in the highest. Does anybody else
have any ideas...
please? -
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 -
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 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. -
Creation of a Popup Menu for a Tree Node
Hi Ppl,
I need to create a Pop-up Menu for a tree node in WebDynpro Application, please give me a "How to .." sort of material or a link which would have same sort of information...
Also, My requirement is to call the pop-up on the right click of mouse on the tree node, please let me know on which event handler I can call it ? Do I require a custom event handler for it ?
Thanks in advance
AnishHi Anish,
You simply add a Tree UI element, and then right-click the tree UI element and insert a TreeNode element.
To the TreeNode element you can add a menu, and then to this menu you can add menu items. When the user right click the tree node, the menu item is displayed. If the user clicks the menu item, the action for the menuitem is run.
Hope that helps.
Daniel -
Version: Jdeveloper 11.1.2.1.0
how to get programmatically tree node value.
i have tried but cann't read value from selected node.
please help me.
here is my application creation steps:
1. New Application
2. Fusion Web Application (ADF) Template
3. Create View Object VOTreeMst
Query:
Select Department_Name,Department_Id
From Departments
4. Create View Object VOTreeChd
Query:
Select Last_Name,Employee_Id,Department_Id
From Employees
5. Create View Link VLTreeMstChd
VOTreeMst.DepartmentId=VOTreeChd.DepartmentId
And Add to Application Module
6. Create page page1 in ViewController
New-->Web Tier-->JSF/Facelets-->Page
Selected Document Type JSP XML
7. Drag VOTreeMst1 From Data Controls into page1
and select Tree-->ADF Tree
8. ADD java Code into selection Listener
public void nodeSelect(SelectionEvent selectionEvent) {
//original selection listener set by ADF
String adfSelectionListener = "#{bindings.VOTreeMst1.treeModel.makeCurrent}";
//make sure the default selection listener functionality is preserved.
//you don't need to do this for multi select trees as the ADF binding
//only supports single current row selection
/* START PRESERVER DEFAULT ADF SELECT BEHAVIOR */
FacesContext fctx = FacesContext.getCurrentInstance();
Application application = fctx.getApplication();
ELContext elCtx = fctx.getELContext();
ExpressionFactory exprFactory = application.getExpressionFactory();
MethodExpression me = null;
me = exprFactory.createMethodExpression(elCtx, adfSelectionListener, Object.class,
new Class[] { SelectionEvent.class });
me.invoke(elCtx, new Object[] { selectionEvent });
/* END PRESERVER DEFAULT ADF SELECT BEHAVIOR */
RichTree tree = (RichTree)selectionEvent.getSource();
TreeModel model = (TreeModel)tree.getValue();
//get selected nodes
RowKeySet rowKeySet = selectionEvent.getAddedSet();
Iterator rksIterator = rowKeySet.iterator();
//for single select configurations, thi sonly is called once
while (rksIterator.hasNext()) {
List key = (List)rksIterator.next();
JUCtrlHierBinding treeBinding = null;
CollectionModel collectionModel = (CollectionModel)tree.getValue();
treeBinding = (JUCtrlHierBinding)collectionModel.getWrappedData();
JUCtrlHierNodeBinding nodeBinding = treeBinding.findNodeByKeyPath(key);
Row rw = nodeBinding.getRow();
//print first row attribute. Note that in a tree you have to determine the node
//type if you want to select node attributes by name and not index
String rowType = rw.getStructureDef().getDefName();
if(rowType.equalsIgnoreCase("VOTreeMst")){
System.out.println("This row is a department: " + rw.getAttribute("DepartmentId"));
else if(rowType.equalsIgnoreCase("VOTreeChd")){
System.out.println("This row is an employee: " + rw.getAttribute("EmployeeId"));
else{
System.out.println("Huh ????");
// ... do more usefuls stuff here
9. when i click on first node it is working but i click on second node it is not working
error message::
<LifecycleImpl> <_handleException> ADF_FACES-60098:Faces lifecycle receives unhandled exceptions in phase INVOKE_APPLICATION 5
javax.el.ELException: java.lang.NullPointerException
at com.sun.el.parser.AstValue.invoke(Unknown Source)
at com.sun.el.MethodExpressionImpl.invoke(Unknown Source)
at org.apache.myfaces.trinidad.component.UIXComponentBase.broadcastToMethodExpression(UIXComponentBase.java:1589)
at org.apache.myfaces.trinidad.component.UIXTree.broadcast(UIXTree.java:237)
<RegistrationConfigurator> <handleError> ADF_FACES-60096:Server Exception during PPR, #1
javax.el.ELException: java.lang.NullPointerException
I have also tried using following code but same problem
public void onTreeSelect(SelectionEvent selectionEvent) {
//original selection listener set by ADF
String adfSelectionListener = "#{bindings.VOTreeMst1.treeModel.makeCurrent}";
//make sure the default selection listener functionality is preserved.
//you don't need to do this for multi select trees as the ADF binding
//only supports single current row selection
/* START PRESERVER DEFAULT ADF SELECT BEHAVIOR */
FacesContext fctx = FacesContext.getCurrentInstance();
Application application = fctx.getApplication();
ELContext elCtx = fctx.getELContext();
ExpressionFactory exprFactory = application.getExpressionFactory();
MethodExpression me = null;
me = exprFactory.createMethodExpression(elCtx, adfSelectionListener, Object.class,
new Class[] { SelectionEvent.class });
me.invoke(elCtx, new Object[] { selectionEvent });
/* END PRESERVER DEFAULT ADF SELECT BEHAVIOR */
RichTree tree = (RichTree)selectionEvent.getSource();
TreeModel model = (TreeModel)tree.getValue();
//get selected nodes
RowKeySet rowKeySet = selectionEvent.getAddedSet();
Iterator rksIterator = rowKeySet.iterator();
//for single select configurations, thi sonly is called once
while (rksIterator.hasNext()) {
List key = (List)rksIterator.next();
JUCtrlHierBinding treeBinding = null;
treeBinding = (JUCtrlHierBinding)((CollectionModel)tree.getValue()).getWrappedData();
JUCtrlHierNodeBinding nodeBinding = treeBinding.findNodeByKeyPath(key);
Row rw = nodeBinding.getRow();
//print first row attribute. Note that in a tree you have to determine the node
//type if you want to select node attributes by name and not index
System.out.println("row: " + rw.getAttribute(0));
But
If i create .jspx page From
Web Tier->Jsp->page Then it is working fine
when i create .jspx page From
Web Tier->JSF\Facelets->page Then it is not working
i need to get value from "Web Tier->JSF\Facelets->page"
is there any help please?You should try Franks generic selectionListener http://www.oracle.com/technetwork/developer-tools/adf/learnmore/25-generic-tree-selection-listener-169164.pdf. For help on hoe to get the selected tree node data check http://www.oracle.com/technetwork/developer-tools/adf/learnmore/26-get-selected-tree-node-data-169165.pdf
Timo -
Does an irrepariable "Invalid B-tree node" = unusable HD?
Hello,
I've decided my external LaCie drive has officially "died," but I want to know if it's truly unuseable or if I can just reformat it and start over (with it) again.
The Drive: a LaCie 300GB with one 40GB scratch partition and one 260GB backup partition.
What happened: After a about a week of erratic/slow disk access to the backup partiton (I'd shrugged it off as a full and fragmented drive), it finally just screeched to a snail's pace - so I could read/write to it, but, for example, copying 5MB file to/from it took about 3mins. I quickly backed up as much as I could off of it to another drive (100GB took 14hrs) and just as it finished copying the last file, it disappeared from my sidebar (though the scratch partition was still visible). I Disk Utility and could see it was unmounted and it's "name" had been reset to "disk5s3". Running the First Aid repair resulted in a quick "Invalid B-tree node size" ... "Error: The underlying task reported failure on exit".
Flash forward three days later: After unsuccessfully running Disk Warrior and Data Rescue for 20hrs (progress estimated it would take 400hrs to complete scan) - I gave up.
Sorry for the long setup, but my question is: can I just "zero" the drive and use it again, or is it "damaged" physically and suitable for a paperweight only. If it's usuable after reformatting, is there a way to test the hardware of the drive to assure it's stable?
Thanks for your time!can I just "zero" the drive and use it again, or is it "damaged" physically and suitable for a paperweight only
Like Dwight I doubt the drive is physically damaged but simply has a damaged catalogue b-tree. The only way you're going to find out though it to erase the drive and write zeros to it. Just be aware that everything on the drive will be lost (though I gather you know that already) if you do this. -
How to cut, copy and paste a tree node in JTree?????
Hi, Java GUI guru. Thank you for your help in advance.
I am working on a File Explorer project with JTree. There are cut, copy and paste item menus in my menu bar. I need three EventAction methods or classes to implements the three tasks. I tried to use Clipboard to copy and paste tree node. But I can not copy any tree node from my tree.
Are there any body has sample source code about cut, copy, and paste for tree? If possible, would you mind send me your sample source code to [email protected]
I would appreciate you very very much for your help!!!!
X.G.Hi, Paul Clapham:
Thank you for your quick answer.
I store the node in a DefaultMutableTreeNode variable, and assign it to another DefaultMutableTreeNode variable. I set up two classes (CopyNode and PasteNode). Here they are as follows:
//CopyNode class
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
public class CopyNode implements ActionListener{
private TreeList jtree;
String treeNodeName;
TreePath currentSelection;
DefaultMutableTreeNode currentNode;
public CopyNode(TreeList t){
jtree = t;
public void actionPerformed(ActionEvent e){
currentSelection = jtree.tree.getSelectionPath();
if(currentSelection != null){
currentNode = (DefaultMutableTreeNode)(currentSelection.getLastPathComponent());
treeNodeName = currentNode.toString();
//PasteNode class
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.event.*;
public class PasteNode extends DefaultMutableTreeNode{
private TreeList jtree;
CopyNode copyNode;
public PasteNode(TreeList t){
jtree = t;
copyNode = new CopyNode(t);
public DefaultMutableTreeNode addObject(Object child){
DefaultMutableTreeNode parentNode = null;
TreePath parentPath = jtree.tree.getSelectionPath();
if(parentPath == null){
parentNode = jtree.root;
else{
parentNode = (DefaultMutableTreeNode)parentPath.getLastPathComponent();
return addObject(parentNode, child, true);
public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, Object child, boolean shouldBeVisible){
DefaultMutableTreeNode childNode = copyNode.currentNode;
if(parent == null){
parent = jtree.root;
jtree.treemodel.insertNodeInto(childNode, parent, parent.getChildCount());
if(shouldBeVisible){
jtree.tree.scrollPathToVisible(new TreePath(childNode.getPath()));
return childNode;
I used these two classes objects in "actionPerformed(ActionEvent e)" methods in my tree:
//invoke copyNode
copyItem = new JMenuItem("Copy");
copyItem.addActionListener(copyNode);
//invoke pasteNode
pasteItem = new JMenuItem("Paste");
pasteItem.addActionListener(
new ActionListener(){
public void actionPerformed(ActionEvent e){
pasteName.addObject(copyName.treeNodeName);
When I run the drive code, making a copy some node from my tree list, I got bunch of error messages.
Can you figour out what is wrong in my two classes? If you have sample code, would you mind mail me for reference.
Thank you very much in advance.
X.G. -
How-to synchronize edit forms for a single View Object tree node entrie
Hi all,
I created a tree from a single View Object,
follow this [http://www.oracle.com/technetwork/developer-tools/adf/learnmore/32-tree-table-from-single-vo-169174.pdf]
then i want to create and synchronize edit forms for tree node entries,
follow this [http://www.oracle.com/technetwork/developer-tools/adf/learnmore/50-synchromize-form-treeselection-169192.pdf]
but it not working when i click child node!!
i found the latter tree from many View Object ,but the former tree from single View Object.
what should i do?
Thanks in advanceHi,
say the tree is built from ViewObject1. In the AM model, create a second View Object instance for this. Say ViewObject2. Create the form from ViewObject2 and the tree from ViewObject1. When creating the tree, use the"Target Data Source" option at the bottom to reference the iterator of ViewObject2. Then create a PartialTrigger on the paneFormLayout that holds the synch form. In the partial trigger property, reference the tree so that when the tree selection changes, the form is updated. Then create a PartialTrigger property on the tree and point it to the submit button of the form so you can show updated values in the tree.
Frank
Maybe you are looking for
-
Internet explorer 6 not playing fair
Hi I have just made this site live and thought everything was ok but have tested in adobe lab browser and everything not ok and I am not sure how to fix it. If I fix it for internet explorer, it doesnt render properly in firefox and other compliant
-
HELP with update to download assistant
I'm trying to download CS6, but I can't do that unless I download an updated version of the download assistant application (1.0.3 to 1.2.4). When I click "download now" the blue bar runs across as if it's finished, but then nothing happens. What do I
-
Have dragged some film clips from the clips panel on to the movie timeline, but when i playback i don't have any sound. I have restarted my mac a few times and re-imported clips but still no sound. Any idea what might be causing this? Thanks Eoin
-
Conversion of digits into numbers
Hi , Is there any procudure of FM to get decimal numbers into integers. For example 6.1 should be 7 . Thanks Satya
-
FYI If you get the free trial of moblie me and you don't want it anymore, it WILL DELETE ALL OF YOUR CALENDAR NOTES!!!! If you want to share your calendar notes with another iPhone or cpu best way to do that is through google calendar. http://www.goo