Stopping tree node expansions
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,
Jim
In jdk1.3 or higher:
tree.setToggleClickCount(-1);
Similar Messages
-
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 PMI 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.
-
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 -
WD ABAP: selecting a tree node from program and scroll to it
Hi guys!
I am using a tree in Web Dynpro ABAP. I would like to select/highlight one node from the coding, without user interaction. Is it possible? I couldn't find any (obvious) way so far...
If it is possible, then let us go a little bit further. Suppose, that the tree grew so big, that cannot fit in the container. Suppose, that you can scroll the tree up/down to see all the nodes. Now, if you mark one tree node from the coding, is it possible somehow, that you scroll the tree automatically, so that the selected node is visible?
I am interested in any solutions within WD ABAP.
If you can only answer one of the questions, that is also appreciated!
Thanks for the help in advance.
Best regards,
Janos Kis
Aerospace&Defense(ERP)Hi Thomas,
thanks for the advice, it works, I have already tried it. The tree node in the lead selection appears highlighted.
The scrolling doesn't work, though. I have tried to put the tree in a scroll container, and I have also tried it without (relying on the browser to scroll). Neither of them worked, it doesn't scroll to the selected node, it remains offscreen. Can you think of a way, to bring it automatically within the visible range? Ideas, anyone?
Actually we would like to implement a search function in the tree, and show the result within the tree (highlight the node, expand, if necessary, and bring it on the screen, if off-screen)
A negative answer is good enough for me, so that I know, that I can stop looking for a solution. Thanks in advance.
Janos -
WebDynpro ABAP tree node collapse trigger event of row selection
Hello expert,
I have a table in my WD abap view, I use MasterColumn to display the tree structure, everything works just fine.
However I encounter one problem:
If I open the tree structure and select one node (table row selection), the event onLeadSelectis triggered, this is correct. However if I collapse any parent nodes (along the tree path) of the selected node, WD puts the selection on the clicked parent and thus the event onLeadSelect is triggered for the parent. This is a strange behavior, because when I collapse a node, I certainly don't want to trigger the onLeadSelect event for the node, becaseu this would invoke the function linked to the event which is only supposed to be triggered when you explicitly select the table row. (BTW, if you don't select any child nodes, then collapse the parent, it does NOT trigger the event).
I've looked into the wdevent data to see if I can differentiate between the event of node collapsing and row selecting, event data is exact same for both cases, thus I have no way to stop the event handler in case of node collapsing.
Anyone had this issue and a solution for this?
Thanks
JaysonHi Jayson,
Its the behavior of the tree element, the lead selection of child is carried over to the parent.
Whenever there is lead selection set and on toggling of tree node, first OnToggle event triggers and then OnLeadSelect triggers. So you can control the execution of onLeadSelect by using EXPANDED parameter of event OnToggle.
Please refer the below steps:
Create an action ON_TOGGLE for the vent OnToggle of tree element and it will be having parameter EXPANDED
Create an attribute in view-->attributes tab GV_EXPANDED
Collect the parameter EXPANDED into gv_expanded
wd_this->gv_expanded = expanded.
Now, you can use wd_this->gv_expanded to control the execution of LEADSELECT logic
Hope this helps you.
Regards,
Rama -
WD ABAP: Recursion Nodes that Repeat Tree Nodes with Embedded Tables ???
At Rich H's suggestion, I'm posting this here as well as in the blogs.
Suppose you've got a tree context with a node that has a table embedded under it. (For example, the TREE_WITH_TABLE view of WDR_TEST_EVNT has this kind of context substructure.) Call this node "NODE_WITH_TABLE."
You now define a recursion node underneath "NODE_WITH_TABLE" and specify "NODE_WITH_TABLE" as the repeated node for this recursion node. Call this recurion node "RECURSION_NODE".
Lo and behold - the table fills properly when you're on any instance of "NODE_WITH_TABLE", but not when you're on an instance of "RECURSION_NODE".
I'm hoping that:
a) I'm doing something wrong;
OR
b) There's an easy work-around/alternative I'm not seeing
OR
c) SAP will give recursion nodes enough memory to carry any table(s) embedded in the nodes they're repeating.
'Cause I sure don't want to have to define "n" levels of tree-nodes that have different copies of the same table(s) embedded in them.
Message was edited by: Armin Reichert/people/david.halitsky/blog/2006/08/16/recursion-nodes-that-repeat-tree-nodes-with-embedded-tables-in-wd-abap-not
Maybe you might want to back out your weblog as it is not really a place to ask these types of questions. Think of it this way, if you are allowed to do this type of weblog, what is stopping any other weblogger. Hence the weblogs would just be another forum, which I don't think anyone wants.
Regards,
Rich Heilman -
Hello All
I am Creating a Tree and It is going to Populate only when the Node is Expanded.
I.E. the Child records are created only when the Node is Expanded.
What we Did is that when we are creating a Parent Node, we are populating a dummy child node to the Parent Node, so that the + sign will be shown.
Now when I am Expanding the + sign, it has to delete the Dummy child node and then create the Child nodes under the Dummy one.
For this One I am unable to Find a solution.
PLEASE HELP ME REGARDING THIS ONE.
THIS PROBLEM IS RELATING TO FORMSIn the when-tree-node-expanded trigger.
Store the system.trigger_node. This is the parent.
Search, starting with the parent, for a child which has the value/label that you gave the dummy node. Did you find one? If yes then delete it.
If you didn't find one then you stop as you've already expanded this node I guess.
After you delete the child you must then add the new children. So loop through the code that produces the list of new children you want, and add them under the parent that you started with.
Hope this helps. -
Receiving Invalid B-tree node size in Disk Utility
My mac mini has recently bit the dust. I did a hard shut down by holding down the power button. Since then I have not been able to bring it back. It started with a folder with a ? in it. Sometimes it sits at the apple logo, and other times it goes to a gray screen and just reboots eventually. I am running Snow Leopard, and I have booted from the install cd. I have tried running Repair Disk in Disk Utility, but I receive the following error: "Invalid node structure Invalid B-tree node size The volume could not be verified completely. Volume repair complete. Updating boot support partitions for the volume as required. Error: Disk Utility can't repair this disk...disk, and restore your backed-up files."
In the pop up window it says "Disk Utility stopped repairing "macintosh HD" Disk Utility can't repair this disk. Back up as many of your files as possible, reformat the disk, and restore your backed-up files. On the left hand side of the window I see 60.01GB ST96812AS Media, and then I see Macintosh HD offset underneath. The Macintosh HD is in light gray and is not mounted. When I try to Mount it it gives me an error and tells me to repair the disk.
My question is do you think Disk Warrior would work or something like that software? I tried to do an Archive and Install, but since the HD won't mount I can't do an installation. Is my HD dead?
Any help would be appreciated!
Sincerely,
MattAs you can see, I received no help from this forum. I ended up replacing the hard drive after trying disk warrior unsuccessfully! I wish you luck and anyone else who has this issue.
<a href="http://www.medicare-plans.net">Medicare Man</a> -
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 can I edit the selected tree node immediately?
I have completed a popup menu ,which appeares when I have a mouse rightclicked event
over the selected tree node.when I selected the popup menu item,i can edit the tree node ,but
I feel that the tree celleditor appear slowly ,what should i do? the following is my code:
menuItemRenameNode.addActionListener(new ActionListener()
public void actionPerformed(ActionEvent ae)
renameNode_ActionPerformed(ae);
void renameNode_ActionPerformed(ActionEvent ae){
setEditable(true);
this.getCellEditor().addCellEditorListener(new CellEditorListener(){
public void editingCanceled(ChangeEvent e){
CellEditor cellEditor =(CellEditor)e.getSource();
System.out.println("editing canceled:"+cellEditor.getCellEditorValue().toString());
protected boolean canEditImmediately(EventObject e){
return true;
public void editingStopped(ChangeEvent e){
CellEditor cellEditor =(CellEditor)e.getSource();
System.out.println("editing stopped:"+cellEditor.getCellEditorValue().toString());Please check the suggestions in the thread: https://forums.adobe.com/thread/692020?tstart=0
Regards,
| T. Ravi Kumar -
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.
Maybe you are looking for
-
How do you get rid of the "adobeacrobat.html" thing at the end of my PDF documents?
-
Trouble with my Adobe Web Premium license
Hello, I asked for assistance a couple of weeks ago, and got an answer that 1/2 way solved my problem. So I'm looking for help to get me all the way there. For background, my original issue was: I recently purchased a new Macbook Air. My other comput
-
Determine hot blocks on interconnect
Hi, I got the below query from the forum...Re: How to determine hot blocks on interconnect and when i ran in my instance.. its show as SQL> select /*+ rule */ de.owner, de.segment_name, de.segment_type, 2 3 ash.event, 4 sum(ash.time_waited)
-
Error Message When Editing Font
I am using Adobe Acrobat 9 Standard. When I try to edit text in a document with TouchUp Text tool, I get an error message: "All or part of the selection has no available system font. You cannot add or delete text using the currently selected font." W
-
Hi I'm beginner learn LabVIEW, I need help about my program for final project. I try to make spirometer using sensor MPX2010dp, differential ammplifier AD620, and Arduino Uno. But when I try to show th result from my hardware to LabVIEW the graphyc