Operations on tree nodes
Hi everyone, it's me again, with another issue =)
I need to be able to rename all node under a specific node in a hierarchy. Let's take this table and the following sample data.
CREATE TABLE organisations
organ_id NUMBER(10) PRIMARY KEY,
parent_id NUMBER(10),
NAME VARCHAR2(255),
CONSTRAINT fk_org_to_parent_org
FOREIGN KEY(parent_id) REFERENCES organisations(organ_id)
Insert into ORGANISATIONS (ORGAN_ID,PARENT_ID,NAME) values (1,null,'Organisation 1');
Insert into ORGANISATIONS (ORGAN_ID,PARENT_ID,NAME) values (2,null,'Organisation 2');
Insert into ORGANISATIONS (ORGAN_ID,PARENT_ID,NAME) values (21,2,'Organisation 21');
Insert into ORGANISATIONS (ORGAN_ID,PARENT_ID,NAME) values (22,2,'Organisation 22');
Insert into ORGANISATIONS (ORGAN_ID,PARENT_ID,NAME) values (221,22,'Organisation 221');
Insert into ORGANISATIONS (ORGAN_ID,PARENT_ID,NAME) values (2211,221,'Organisation 2211');
Insert into ORGANISATIONS (ORGAN_ID,PARENT_ID,NAME) values (3,null,'Organisation 3');
Insert into ORGANISATIONS (ORGAN_ID,PARENT_ID,NAME) values (31,3,'Organisation 31');
Insert into ORGANISATIONS (ORGAN_ID,PARENT_ID,NAME) values (311,31,'Organisation 311');
Insert into ORGANISATIONS (ORGAN_ID,PARENT_ID,NAME) values (3111,311,'Organisation 3111');
Insert into ORGANISATIONS (ORGAN_ID,PARENT_ID,NAME) values (32,3,'Organisation 32');
Insert into ORGANISATIONS (ORGAN_ID,PARENT_ID,NAME) values (321,32,'Organisatin 321');
Insert into ORGANISATIONS (ORGAN_ID,PARENT_ID,NAME) values (3211,321,'Organisation 3211');
Insert into ORGANISATIONS (ORGAN_ID,PARENT_ID,NAME) values (3212,321,'Organisation 3212');
Insert into ORGANISATIONS (ORGAN_ID,PARENT_ID,NAME) values (313212,3212,'Organisation with an id containing 31.');I'd like to rename some nodes in the tree. For example, how can I for example add the '- renamed' to all nodes under the node with organ id = 31?
I tried the following but it's not good because whenever I have another ID containing the number 31, I have a wrong result.
SELECT organ_id, lpad(' ', LEVEL * 2) || name,
-- sys_connect_by_path(organ_id, ','),
case when instr( sys_connect_by_path(organ_id, ','), '31') > 0 then
name || '- renamed'
else
name
end
FROM organisations
START WITH parent_id is null
CONNECT BY PRIOR organ_id = parent_id;The following query does the job:
select organ_id, lpad(' ', level * 2) || name,
-- sys_connect_by_path(organ_id, ','),
case when organ_id IN (SELECT organ_id
from organisations
start with organ_id = 31
CONNECT BY prior organ_id = parent_id) then
name || '- renamed'
else
name
end
from organisations
start with parent_id is null
CONNECT BY PRIOR organ_id = parent_id;I wanted to know if it was possible without the sub select?
Thanks
Hi,
user13117585 wrote:
... In this case, I want to add something in the end of the name of both organisations (31 & 221)221) and all their children nodes.It will be worth your time to learn and use the right terms. If you don't, you'll waste a lot of time (both yours and that of the people trying to help you) by getting answers to what you said, rather than what you wanted.
"Child" means an node exactly one level down the hierarchy, a "descendant" means a node any number of levels down.
In your sample data, 311 is a child of 31, and 311 is also a descendant of 31. (Children are always descendants.)
3111 is not a child of 31, but 3111 is a descendant of 31. (Descendants are not always children.)
If you want to mark all the descendants of organ_ids found in table t:
SELECT o.organ_id
, LPAD (' ', LEVEL * 2) || o.name AS name
, CASE
WHEN INSTR ( SYS_CONNECT_BY_PATH ( NVL2 ( t.organ_id
, '+'
) > 0
THEN name || '- renamed'
ELSE name
END AS name_r
FROM organisations o
LEFT OUTER JOIN t ON o.organ_id = t.organ_id
START WITH o.parent_id IS NULL
CONNECT BY PRIOR o.organ_id = o.parent_id;As you were doing before, display SYS_CONNECT_BY_PATH to see what it's doing. You'll see, that, instead of producing a string like
',3,31,311', which contains information that can lead you to what you need to know, the query above produces a sting like
',+,-,+', which contains exactly what you need to know.
Similar Messages
-
How to trigger an ActionListener in different class on click of a tree node
Hi guyz,
There are three panels inside my main Frame
-->TopPanel,MiddlePanel and BottomPanel. I have a tree structure inside a panel. This panel along with couple more panels is in MiddlePanel. My main class is "mainClass.java". Inside that i have an actionListener for a specific button. I need to trigger that actionListener when i click one of the tree nodes in the panel i specified before. The problem is that my MiddlePanel is itself a different ".java" file which is being called in my "mainClass" when a specific button is clicked. There are different buttons in my "mainClass" file and for each one i am creating different MiddlePanels depending on the buttons clicked.
So, if i click the tree node, i need to remove the MiddlePanel and recreate the MiddlePanel(One that will be created when a different button in the mainClass file is clicked). i.e., i need to trigger the actionListener for that corresponding button. Is there a way to do it?use this code to call different panel by selecting tree node.....ok
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.sql.SQLException;
import javax.swing.event.*;
class MainTree extends JFrame
private static final long serialVersionUID = 1L;
CardLayout cl = new CardLayout();
JPanel panel = new JPanel(cl);
public MainTree() throws Exception
JPanel blankPanel = new JPanel();
blankPanel.setBorder(BorderFactory.createTitledBorder("Blank Panel"));
panel.add(blankPanel,"0");
panel.add(blankPanel,BorderLayout.CENTER);
panel.setPreferredSize(new Dimension(800, 100));
setSize(1000, 700);
setLocationRelativeTo(null);
setDefaultCloseOperation(EXIT_ON_CLOSE);
// getContentPane().setLayout(new GridLayout(1,2));
getContentPane().setLayout(new BorderLayout());
ConfigTree test = new ConfigTree();
DefaultMutableTreeNode mainTree = (DefaultMutableTreeNode)test.buildTree();
JTree tree = new JTree(mainTree);
tree.setCellRenderer(new DefaultTreeCellRenderer(){
private static final long serialVersionUID = 1L;
public Component getTreeCellRendererComponent(JTree tree,Object value,
boolean sel,boolean expanded,boolean leaf,int row,boolean hasFocus){
JLabel lbl = (JLabel)super.getTreeCellRendererComponent(tree,value,sel,expanded,leaf,row,hasFocus);
NodeWithID node = (NodeWithID)((DefaultMutableTreeNode)value).getUserObject();
if(node.icon != null)lbl.setIcon(node.icon);
return lbl;
getContentPane().add(new JScrollPane(tree));
loadCardPanels((DefaultMutableTreeNode)((DefaultTreeModel)tree.getModel()).getRoot());
getContentPane().add(panel,BorderLayout.EAST);
getContentPane().add(blankPanel,BorderLayout.WEST);
// getContentPane().add(panel);
tree.addTreeSelectionListener(new TreeSelectionListener(){
public void valueChanged(TreeSelectionEvent tse){
NodeWithID node =(NodeWithID)((DefaultMutableTreeNode)((TreePath)tse.getPath())
.getLastPathComponent()).getUserObject();
if(node.nodePanel != null)
String cardLayoutID = node.ID;
cl.show(panel,cardLayoutID);
cl.show(panel,"0");
public void loadCardPanels(DefaultMutableTreeNode dmtn)
for(int x = 0; x < dmtn.getChildCount(); x++)
if(((DefaultMutableTreeNode)dmtn.getChildAt(x)).isLeaf() == false)
loadCardPanels((DefaultMutableTreeNode)dmtn.getChildAt(x));
NodeWithID node = (NodeWithID)((DefaultMutableTreeNode)dmtn.getChildAt(x)).getUserObject();
if(node.nodePanel != null)
String cardLayoutID = node.ID;
panel.add(cardLayoutID,node.nodePanel);
public static void main(String[] args) throws Exception{new MainTree().setVisible(true);}
class ConfigTree
public Object buildTree() throws Exception
NodeWithID n0 = new NodeWithID("HelpDesk","");
NodeWithID n1 = new NodeWithID("Administrator",n0.nodeName);
NodeWithID n2 = new NodeWithID("Report Form",n1.nodeName,new Tree().getContentPane());
NodeWithID n3 = new NodeWithID("Create User",n2.nodeName,new JPanel());
NodeWithID n4 = new NodeWithID("Unlock User",n2.nodeName,new unlockui().getContentPane());
NodeWithID n5 = new NodeWithID("List User",n2.nodeName,new JPanel());
NodeWithID n6 = new NodeWithID("Assign Role",n2.nodeName,new AssignRole());
NodeWithID n9 = new NodeWithID("Operator",n1.nodeName,new JPanel());
NodeWithID n10 = new NodeWithID("Create Ticket",n9.nodeName,new JPanel());
NodeWithID n11 = new NodeWithID("My Ticket",n9.nodeName,new JPanel());
NodeWithID n12 = new NodeWithID("All Ticket",n9.nodeName,new JPanel());
NodeWithID n13 = new NodeWithID("Event Viewer",n1.nodeName,new JPanel());
DefaultMutableTreeNode top = new DefaultMutableTreeNode(n0);
DefaultMutableTreeNode branch1 = new DefaultMutableTreeNode(n1);
top.add(branch1);
DefaultMutableTreeNode node1_b1 = new DefaultMutableTreeNode(n2);
DefaultMutableTreeNode n1_node1_b1 = new DefaultMutableTreeNode(n3);
DefaultMutableTreeNode n2_node1_b1 = new DefaultMutableTreeNode(n4);
DefaultMutableTreeNode n3_node1_b1 = new DefaultMutableTreeNode(n5);
DefaultMutableTreeNode n4_node1_b1 = new DefaultMutableTreeNode(n6);
branch1.add(node1_b1);
branch1.add(n1_node1_b1);
branch1.add(n2_node1_b1);
branch1.add(n3_node1_b1);
branch1.add(n4_node1_b1);
DefaultMutableTreeNode node4_b1 = new DefaultMutableTreeNode(n9);
DefaultMutableTreeNode n1_node4_b1 = new DefaultMutableTreeNode(n10);
DefaultMutableTreeNode n2_node4_b1 = new DefaultMutableTreeNode(n11);
DefaultMutableTreeNode n3_node4_b1 = new DefaultMutableTreeNode(n12);
node4_b1.add(n1_node4_b1);
node4_b1.add(n2_node4_b1);
node4_b1.add(n3_node4_b1);
DefaultMutableTreeNode node5_b1 = new DefaultMutableTreeNode(n13);
branch1.add(node1_b1);
branch1.add(node4_b1);
branch1.add(node5_b1);
return top;
class NodeWithID
String nodeName;
String ID;
JPanel nodePanel;
ImageIcon icon;
public NodeWithID(String nn,String parentName)
nodeName = nn;
ID = parentName+" - "+nodeName;
public NodeWithID(String nn,String parentName,Container container)
this(nn,parentName);
nodePanel = (JPanel) container;
nodePanel.setBorder(BorderFactory.createTitledBorder(ID + " Panel"));
public NodeWithID(String nn,String parentName,JPanel p, ImageIcon i)
this(nn,parentName,p);
icon = i;
public String toString(){return nodeName;}
} -
Selecting a RichTree component tree node
Hi,
How do I get the selected tree node in a RichTree component?. I would like to select the node with the mouse and possibly use the popup menu to initiate an action (e.g. delete). How do I add an item to the popup menu to do this? I'm using the RichTree component in JDev 11g. Any sample code would be helpful.
Thanks
ColinColin,
To perform some operation on node selection within af:tree component you simply need to create a selectionlistener and decorate the tree component with the listener you implemented. For the context-menu you describe the af:tree has an attribute named contextMenuId. Set the value of this attribute to equal the id of an af:popup that contains an af:menu that represents the menu that you want displayed on a right-click. Below is a link to the tag doc for the af:tree component
http://www.oracle.com/technology/products/adf/adffaces/11/doc/multiproject/adf-richclient-api/tagdoc/af_tree.html
--Ric -
Hi All,
Can anyone help me to implement Tree node in F4 Search help?
Thanks
E KarthikeyanSAP has provided a lot of sample programs for developing tree structures. Just go to SE38, type BCALVTREE and hit F4. You'll get different sample programs with a range of operations on trees
Go through the link,
http://www.sapdevelopment.co.uk/reporting/alv/alvtree.htm
Slowly check this code..you will get idea of how to develop tree structure.
REPORT y_hierarchies_in_tables
NO STANDARD PAGE HEADING.
PARAMETER: g_group TYPE grpname. " DEFAULT 'Z_GLAB0000'.
DATA:
g_setid TYPE setid,
g_class TYPE setclass.
DATA: lt_hier TYPE STANDARD TABLE OF sethier,
lt_val TYPE STANDARD TABLE OF setvalues.
DATA: hier LIKE sethier OCCURS 0 WITH HEADER LINE,
val LIKE setvalues OCCURS 0 WITH HEADER LINE,
setinfo LIKE setinfo OCCURS 0 WITH HEADER LINE.
DATA: zaccbas(20) TYPE c OCCURS 0 WITH HEADER LINE.
DATA: miss_val LIKE setvalues-from OCCURS 0 WITH HEADER LINE.
DATA: table_name TYPE tabname,
field_name TYPE setfld.
DATA: ambiguity_flag TYPE c.
Ambiguity check
PERFORM ambiguity_check.
Display Records
PERFORM display_records.
*& Form AMBIGUITY_CHECK
Ambiguity check
FORM ambiguity_check .
DATA: it_abaplist LIKE abaplist OCCURS 0 WITH HEADER LINE.
DATA: BEGIN OF it_ascilist OCCURS 0,
zeile(256) TYPE c,
END OF it_ascilist.
DATA: flag.
SUBMIT rgsovl00 "VIA SELECTION-SCREEN
WITH p_shrtn = g_group
WITH path = 'X'
EXPORTING LIST TO MEMORY
AND RETURN.
CALL FUNCTION 'LIST_FROM_MEMORY'
TABLES
listobject = it_abaplist
EXCEPTIONS
not_found = 1
OTHERS = 2.
CALL FUNCTION 'LIST_TO_ASCI'
TABLES
listasci = it_ascilist
listobject = it_abaplist
EXCEPTIONS
empty_list = 1
list_index_invalid = 2
OTHERS = 3 .
LOOP AT it_ascilist.
IF it_ascilist-zeile = text-001.
flag = 'X'.
ENDIF.
IF flag = 'X' AND
it_ascilist-zeile = text-002.
ambiguity_flag = 'X'.
CLEAR flag.
ENDIF.
ENDLOOP.
FREE MEMORY.
ENDFORM. " AMBIGUITY_CHECK
*& Form DISPLAY_RECORDS
Display the Records
FORM display_records .
PERFORM get_records.
PERFORM header_data.
PERFORM item_data.
ENDFORM. " DISPLAY_RECORDS
*& Form GET_RECORDS
Get all the Node values
FORM get_records .
Get the ID name for the Hierarchy
CALL FUNCTION 'G_SET_GET_ID_FROM_NAME'
EXPORTING
shortname = g_group
setclass = g_class
old_setid = g_setid
IMPORTING
new_setid = g_setid.
Get the Table and Field name for the Top Node
CALL FUNCTION 'G_SET_GET_INFO'
EXPORTING
setname = g_setid
no_set_title = 'X'
use_table_buffer = 'X'
IMPORTING
info = setinfo.
table_name = setinfo-tabname.
field_name = setinfo-fld.
Get all the Nodes for the Hierarchy
CALL FUNCTION 'G_SET_TREE_IMPORT'
EXPORTING
no_descriptions = ' '
no_rw_info = 'X'
setid = g_setid
TABLES
set_hierarchy = lt_hier
set_values = lt_val.
hier[] = lt_hier.
val[] = lt_val.
SELECT (field_name) FROM (table_name) INTO TABLE zaccbas.
LOOP AT zaccbas.
READ TABLE val WITH KEY FROM = zaccbas.
IF sy-subrc = 0.
DELETE zaccbas.
CLEAR zaccbas.
DELETE val INDEX sy-tabix.
CLEAR val.
ENDIF.
ENDLOOP.
ENDFORM. " GET_RECORDS
*& Form HEADER_DATA
Header Data
FORM header_data .
DATA: desc TYPE settext.
READ TABLE hier WITH KEY fieldname = field_name
shortname = g_group.
IF sy-subrc = 0.
desc = hier-descript.
ENDIF.
SKIP.
WRITE: 'Node :',g_group.
WRITE:75 'User name :', sy-uname.
WRITE:/ 'Description :', desc.
WRITE:75 'Date:', sy-datum.
WRITE:/ 'Table Name :' , table_name.
WRITE:75 'Time:', sy-timlo.
WRITE:/ 'Field Name :', field_name.
write:75 'Client:', SY-MANDT.
skip.
IF ambiguity_flag = 'X'.
WRITE:/ 'Ambiguity Check :'. WRITE: 'Success' COLOR 5.
ELSE.
WRITE:/ 'Ambiguity Check :'. WRITE: 'Failed' COLOR 6 .
ENDIF.
WRITE:/ sy-uline.
WRITE:/37 'Validation for Hierarchy'.
WRITE:/ sy-uline.
ENDFORM. " HEADER_DATA
*& Form ITEM_DATA
Output Report for Nodes
FORM item_data .
IF NOT zaccbas[] IS INITIAL.
WRITE:/ 'Missing Records from Hierarchy' COLOR 3.
LOOP AT zaccbas.
WRITE:/ zaccbas.
ENDLOOP.
ENDIF.
IF NOT val[] IS INITIAL.
SKIP 1.
WRITE:/ 'Additional Records in Hierarchy' COLOR 3.
LOOP AT val.
WRITE:/ val-from. ", 28 val-DESCRIPT.
ENDLOOP.
ELSEIF ZACCBAS[] IS INITIAL.
WRITE:/ 'No Missing Records Found' COLOR 3.
ENDIF.
ENDFORM. " ITEM_DATA
Thanks,
Sakthi C
*Rewards if useful* -
Commandtoolbarbutton enabling/disabling based on tree node selection
i am using the tree tag to generate a set of nodes and every node is a command link.... i have a set of commandtoolbarbuttons on top of the tree... the functionality i am trying to obtain is on press of the tree node( i.e, command link ) the commantoolbarbuttons are enabled or disabled.. on press of link i am able to get the tree node selected in the backing bean, and also i am setting some variables for the "disabled" attribute of commandtoolbarbutton. The problem i am facing here is i have a partialtrigger attribute in the commandtoolbarbutton pointing to the commandlink id. But the partial trigger is unable to identify the command link id outside the tree. And i cannot put the commandtoolbar buttons inside the tree...
Can anyone please let me know how can i resolve this?? or is there anyother approach??
The source code is as mentioned below...
<af:panelGroupLayout layout="horizontal" halign="right">
<f:facet name="separator">
<af:spacer width="5px"/>
</f:facet>
<af:toolbox id="mainTab_box" >
<af:toolbar id="mainTab_bar">
<af:spacer width="80"/>
<af:commandToolbarButton icon="/resources/images/new_ena.png" partialSubmit="true"
shortDesc="New" id="ctb1_mainTab" disabled="#{nodeSelectionHandler.createToolbar}" partialTriggers="cl1"/>
<af:commandToolbarButton icon="/resources/images/update_ena.png" partialSubmit="true"
shortDesc="Update" id="ctb2_mainTab" disabled="#{nodeSelectionHandler.editToolbar}" partialTriggers="cl1"/>
<af:commandToolbarButton icon="/resources/images/delete_ena.png" partialSubmit="true"
shortDesc="Delete" id="ctb3_mainTab" disabled="#{nodeSelectionHandler.cancelToolbar}" partialTriggers="cl1"/>
<af:commandToolbarButton icon="/resources/images/importIcon.png" partialSubmit="true"
shortDesc="Import" id="ctb4_mainTab" disabled="#{nodeSelectionHandler.exportToolbar}" partialTriggers="cl1"/>
<af:commandToolbarButton icon="/resources/images/exportIcon.png" partialSubmit="true"
shortDesc="Export" id="ctb5_mainTab" disabled="#{nodeSelectionHandler.importToolbar}" partialTriggers="cl1"/>
</af:toolbar>
</af:toolbox>
</af:panelGroupLayout>
<af:panelGroupLayout layout="scroll">
<af:tree var="node"
value="#{browserTreeModel}"
id="browsertree" inlineStyle="min-width:200px;min-height:400px;width:100%;height:100%"
rowSelection="single" clientComponent="true" contentDelivery="immediate"
>
<f:facet name="nodeStamp">
<af:panelGroupLayout id="pgl10">
<af:image id="nodeIcon"
inlineStyle="margin-right:3px; vertical-align:middle; height:16px; width:16px;"
shortDesc="directory icon" rendered="#{node.destination != null}"
source="#{node.destination}"/>
<af:commandLink text="#{node.text}"
id="cl1"
disabled="false" partialSubmit="true"
actionListener="#{nodeSelectionHandler.selectionPerformed}" >
<f:attribute name="nodeId" value="#{node.id}"/>
<f:attribute name="operation" value="#{node.associatedOperation}"/>
</af:commandLink>
</af:panelGroupLayout>
</f:facet>
</af:tree>
</af:panelGroupLayout>With apologies, you're not aware of ELUtils class devised by Steve Muench:
package view;
import javax.faces.context.FacesContext;
import javax.faces.el.MethodBinding;
import javax.faces.el.ValueBinding;
public class ELUtils {
public static boolean test(String booleanExpr) {
return Boolean.TRUE.equals(get(booleanExpr));
public static String getAsStringWithDefault(String expr, String defaultExpr) {
return (String)getWithDefault(expr, defaultExpr);
public static String getAsString(String expr) {
return (String)get(expr);
public static Integer getAsInteger(String expr) {
return (Integer)get(expr);
public static Object get(String expr) {
FacesContext fc = FacesContext.getCurrentInstance();
ValueBinding vb = fc.getApplication().createValueBinding(expr);
return vb.getValue(fc);
public static Object getWithDefault(String expr, String defaultExpr) {
Object exprVal = get(expr);
return exprVal != null ? exprVal : get(defaultExpr);
public static void set(String expr, String value) {
Object valToSet = value;
if (isELExpr(value)) {
valToSet = get(value);
set(expr, valToSet);
public static void set(String expr, Object value) {
FacesContext fc = FacesContext.getCurrentInstance();
ValueBinding vb = fc.getApplication().createValueBinding(expr);
vb.setValue(fc, value);
private static boolean isELExpr(Object o) {
if (o instanceof String) {
String str = (String)o;
str.trim();
return str.startsWith("#{") && str.endsWith("}");
return false;
public static Object invokeMethod(String expr, Class[] paramTypes, Object[] params) {
FacesContext fc = FacesContext.getCurrentInstance();
MethodBinding mb = fc.getApplication().createMethodBinding(expr, paramTypes);
return mb.invoke(fc, params);
public static Object invokeMethod(String expr, Class paramType, Object param) {
return invokeMethod(expr, new Class[] { paramType }, new Object[] { param });
}Try that.
CM. -
Tree node selection handler...
Hi i am having a tree of nodes..
I am looking for a functionality where on the click of the tree node ( i.e, on just clicking or selecting the disabled command link ), the af:commandToolbarButton icons on the toolbar are enabled or disabled. Can anyone please let me know how can i do this??
please find the tree code as mentioned below...
<af:tree var="node"
value="#{tree}"
id="brtree" inlineStyle="min-width:200px;min-height:400px;width:100%;height:100%"
rowSelection="single" clientComponent="true" contentDelivery="immediate">
<f:facet name="nodeStamp">
<af:panelGroupLayout id="pgl10">
<af:image id="nodeIcon"
inlineStyle="margin-right:3px; vertical-align:middle; height:16px; width:16px;"
shortDesc="directory icon" rendered="#{node.destination != null}"
source="#{node.destination}"/>
<af:commandLink text="#{node.text}"
id="cl1"
disabled="#{not node.renderAsLink}" partialSubmit="true"
actionListener="#{nodeSelectionHandler.selectionPerformed}">
<f:attribute name="nodeId" value="#{node.id}"/>
<f:attribute name="operation" value="#{node.associatedOperation}"/>
</af:commandLink>
</af:panelGroupLayout>
</f:facet>
</af:tree>Try this.
Change your tree as follows:
<af:tree id="myTree" value="#{bindings.NodesViewTree.treeModel}" selectionListener="#{treeBean.onTreeSelection}"...
(Assuming your tree's binding is called "NodesViewTree")
...note the use of the selectionListener calling our bean's onTreeSelection method.
In your bean:
boolean toolbarItem1Enabled = true; // also create the appropriate getter/setter
boolean toolbarItem2Enabled = true; // also create the appropriate getter/setter
public void onTreeSelection(SelectionEvent selectionEvent) {
ELUtils.invokeMethod("#{bindings.NodesViewTree.treeModel.makeCurrent}", SelectionEvent.class, selectionEvent);
FacesCtrlHierBinding hierBinding = (FacesCtrlHierBinding)AdfUtils.findCtrlBinding("NodesViewTree");
RichTree richTree = (RichTree)selectionEvent.getSource();
RowKeySet rowKeySet = richTree.getSelectedRowKeys();
Object key = rowKeySet.iterator().next();
richTree.setRowKey(key);
JUCtrlHierNodeBinding node = (JUCtrlHierNodeBinding)richTree.getRowData();
String someValue = (String)node.getAttribute("someValue"); // assuming String attribute
if (/* make some decision about enabling/disabling fields based on selected node's someValue */) {
toolbarItem1Enabled = false;
toolbarItem2Enabled = false;
} else {
toolbarItem1Enabled = false;
toolbarItem2Enabled = false;
}Then in your command items modify them as follows:
<af:commandMenuItem disabled="#{treeBean.toolbarItem1Enabled}" partialTriggers="myTree"}>
<af:commandMenuItem disabled="#{treeBean.toolbarItem2Enabled}" partialTriggers="myTree"}>
Please note I haven't tested the exact solution above, I've just cut and copied a bunch of code in from different sources. However it should give you the thread on a possible approach.
Cheers,
CM. -
Post Back Tree view when tree node check changed
Hi everyone,
I have a tree view, both child and parent have check box. I want to check all the child on the parent selection.
I try "SelectedNodeChanged" but the page doesn't post back to fire my function.
I know I can use javascript to post back the page, but is there any other way to post back my page without javascript???
Thnaks in advance.Hi everyone,
I have a tree view, both child and parent have check box. I want to check all the child on the parent selection.
I try "SelectedNodeChanged" but the page doesn't post back to fire my function.
I know I can use javascript to post back the page, but is there any other way to post back my page without javascript???
Thnaks in advance.
Assuming this is a WinForm application (it looks like it may not be), the following works pretty well:
Option Strict On
Option Explicit On
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles MyBase.Load
With TreeView1
.CheckBoxes = True
.ShowLines = True
.ShowPlusMinus = True
.ShowRootLines = True
.ExpandAll()
End With
End Sub
' Updates all child tree nodes recursively.
Private Sub CheckAllChildNodes(ByVal treeNode As TreeNode, ByVal nodeChecked As Boolean)
Dim node As TreeNode
For Each node In treeNode.Nodes
node.Checked = nodeChecked
If node.Nodes.Count > 0 Then
' If the current node has child nodes, call the CheckAllChildsNodes method recursively.
Me.CheckAllChildNodes(node, nodeChecked)
End If
Next node
End Sub
' NOTE This code can be added to the BeforeCheck event handler instead of the AfterCheck event.
' After a tree node's Checked property is changed, all its child nodes are updated to the same value.
Private Sub node_AfterCheck(ByVal sender As Object, ByVal e As TreeViewEventArgs) Handles TreeView1.AfterCheck
' The code only executes if the user caused the checked state to change.
If e.Action <> TreeViewAction.Unknown Then
If e.Node.Nodes.Count > 0 Then
' Calls the CheckAllChildNodes method, passing in the current
' Checked value of the TreeNode whose checked state changed.
Me.CheckAllChildNodes(e.Node, e.Node.Checked)
End If
End If
End Sub
End Class
The reference for that is this MSDN document.
If you're looking for a true tri-state operation though, honestly you might want to look at some third-party controls.
I hope that helps. :)
Please call me Frank :) -
Context menu for tree node cannot be accessed in IE 8 (Jdev 11.1.2)
We use an af:tree with context menus for performing operations on each node. In IE 8 when you hover over a node before right clicking, "tooltip" text appears which basically just re-displays the text of the node. Even though the tooltip text is annoying, the context menu worked fine in 11.1.1.4, but now in 11.1.2 when you right-click on that tooltip text you get the "normal" browser context menu for text -- we no longer get our custom context menu.
You can see this same problem on the tree in the rich faces demo: http://jdevadf.oracle.com/adf-richclient-demo/
Sometimes, if you're quick enough, you can get the custom context menu to work, but it seems that once you've hovered long enough over one node to get the standard context menu, you're stuck and any node you click on will display the browser's normal context menu.
This is a big problem for us because we rely on these context menus and most of our administrative users are on IE 8. Is there a workaround or can the tooltip text somehow be shut off? It doesn't appear in Firefox so Firefox works fine.
Thanks.
-EdHi,
if this works on IE 7 you can force the app to run in IE7 compatibility mode
See "Run ADF Faces applications with IE 9 in IE 8 compatibility mode" http://www.oracle.com/technetwork/developer-tools/adf/learnmore/april2011-otn-harvest-367335.pdf
Works the same for IE8 to IE7. This then gives you a solution for until the issue is solved
Btw.: If users click onto the folder icon (not the text, which brings up the tool tip) then the context menu work. I'll file a bug anyway
Frank -
Urgent! the name of tree node can't show completely
I create a tree dynamicly using data from database;when i want to add a new node to the tree.it will be added at the right place imediately but it's name will not show completely.
for example, i want to add a new node which name is "department",but the name on the tree it shown will be "departm...", i don't know what cause the 3 dot followed and how to remove the dot.
Can anybody tell me why? Thanks a lotI use a IconNode which extend DefaultMutableTreeNode to create the node.
following is the IconNode:
import java.util.*;
import javax.swing.*;
import javax.swing.tree.*;
* @version 1.1 06/19/99
public class IconNode extends DefaultMutableTreeNode {
protected Icon icon;
protected String iconName;
protected boolean isActive=false;
public IconNode() {
this(null);
public IconNode(Object userObject) {
this(userObject, true, null);
public IconNode(Object userObject, boolean allowsChildren
, Icon icon) {
super(userObject, allowsChildren);
this.icon = icon;
public void setIcon(Icon icon) {
this.icon = icon;
public Icon getIcon() {
return icon;
public boolean isActive(){
return this.isActive;
public void setActive(boolean flag){
this.isActive=flag;
public String getIconName() {
if (iconName != null) {
return iconName;
else {
String str = userObject.toString();
int index = str.lastIndexOf(".");
if (index != -1) {
return str.substring(++index);
else {
return str;
public void setIconName(String name) {
iconName = name;
following is the operation of adding node:
private IconNode addObject(Object child) {
IconNode parentNode = null;
TreePath parentPath = appQueueTree.getSelectionPath();
if (parentPath == null) {
parentNode = rootNode;
else {
parentNode = (IconNode)
(parentPath.getLastPathComponent());
return addObject(parentNode, child, true);
private IconNode addObject(IconNode parent,
Object child,
boolean shouldBeVisible) {
IconNode childNode = new IconNode(child);
// TreeNodeData is a value object contains the data of node.
TreeNodeData temp=(TreeNodeData)child;
int flag=temp.getNodeType();// get the type of node
//to set the right icon of node
switch(flag){
case 1://childNode.setIcon();
break;
case 2:childNode.setIcon(leafIcon);
break;
case 3:childNode.setIcon(connectedDepartmentIcon);
if (parent == null) {
parent = rootNode;
treeModel.insertNodeInto(childNode, parent,
parent.getChildCount());
//Make sure the user can see the lovely new node.
if (shouldBeVisible) {
//to scroll the tree path to node newly be added.
appQueueTree.scrollPathToVisible(new TreePath(childNode.getPath()));
return childNode; -
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.
Maybe you are looking for
-
How to block an Goods Receipt...for a PO not invoiced yet.
Dear friends , We have one new situation for one specific foreign vendor where we need to block the goods receipt if no Invoice Receipt is done yet. we know that is possible to block invoice receipt without the GR...but we need exactly the inverse o
-
When I am connected to my home wifi, it says I am connected but the 4G icon doesn't go away. How can I make that go away when I am connected?
-
STS: Few Questions about STS ?
Hi All, Right now, I'm working on STS for IP. I have some questions about it: 1. Every time I execute t-code BPS_STS_START, it launch the STS Web Application with different port and HTTP. The port should be 8444, and HTTP should be HTTPS . I've alrea
-
Hi, I have a new MacBook as of last week. Installed Office 2004 (stu/teacher) and had some issues with it (error messages etc) so removed and reinstalled -- this turned out to be unnecessary as what I really needed to do was download the update from
-
Hi can u please help me out to display multiple [b]thumbnail images[/b]
hi, hi, please help me out! please help me out!! I need to display multiple thumbnail images on the jframe or on a jpanel . From the database where the path of the images are stored say i should first get thumbnail of the images and then display any