Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Interested in getting your voice heard by members of the Developer Marketing team at Oracle? Check out this post for AppDev or this post for AI focus group information.

Dynamic JTree from database query,how 2 build JTree wth dynamic hierarchy ?

843805Dec 5 2005 — edited Apr 17 2006
i need to create JTree dynamically from database query, below my script for table and table data (my database is Oracle):

create table tvr_jv_menus(menu_id number, menu_name varchar2(50), menu_description varchar2(4000), menu_parent_id number, menu_icon_path varchar2(100), menu_type number, menu_status number);

insert into tvr_jv_menus values (1,'File','Default Menu',null,'/img/file.jpg',1,1);
insert into tvr_jv_menus values (2,'Process','Process Menu',null,'/img/proc.jpg',1,1);
insert into tvr_jv_menus values (3,'Connect','Connect to Oracle',1,'/img/conn.jpg',2,1);
insert into tvr_jv_menus values (4,'Exit','Close Application',1,'/img/file.jpg',2,1);
insert into tvr_jv_menus values (5,'Manual','Manual Process',2,'/img/manual.jpg',1,1);
insert into tvr_jv_menus values (6,'Automation','Automatic Process',2,'/img/auto.jpg',1,1);
insert into tvr_jv_menus values (7,'Drive','Manual Drive Process',5,'/img/mndrive.jpg',2,1);
insert into tvr_jv_menus values (8,'Drive','Automatic Drive Process',6,'/img/autodrive.jpg',2,1);
insert into tvr_jv_menus values (9,'Shoot','Automatic Shoot Process',6,'/img/autoshoot.jpg',2,1);

commit;

then using this query i can populate hierarchial data :

select level, menu_id, menu_name, menu_description, menu_parent_id, menu_icon_path, menu_type, menu_status
from tvr_jv_menus
connect by prior menu_id = menu_parent_id
start with menu_parent_id is null

data resulted from above query should be like this :
LEVEL MENU_ID MENU_NAME MENU_PARENT_ID MENU_TYPE
1 1 File 1
2 3 Connect 1 2
2 4 Exit 1 2
1 2 Process 1
2 5 Manual 2 1
3 7 Drive 5 2
2 6 Automation 2 1
3 8 Drive 6 2
3 9 Shoot 6 2
level column indicating the hierarchy of the treenode, its parentnode is indicated by menu_parent_id column.

menu_name column should be the node name, which is visually seen by the user.

menu_type indicating whether a node is contained by an event or not. Value 1 means the node doesn't have any event, otherwise, 2 means the node have event. For example menu_name = 'Exit' has menu_type value equals to 2, so if exit node is doubleclicked then it should trigger an event to exit the application.

menu_description should be the tooltip of the node and menu_icon_path should be the path for the node's icon.

the problem are, users are freely creating their menu. it can be 3 level hierarchy or more. and users are freely too to determine the action for each menu which its menu_type = 2.

how to create dynamic JTree with these requirements ?

thanks' alot !!!

Comments

843805
I have created some classes to create JTree based on data from database as posted before. But i got error ClassCastException
--------------------------------------------------------------------------------------------
Exception in thread "main" java.lang.ClassCastException: javax.swing.tree.DefaultMutableTreeNode
at usermanagementconsole.gui.data.TreeDataModel.isLeaf(TreeDataModel.java:46)
at javax.swing.JTree.setModel(JTree.java:704)
at javax.swing.JTree.<init>(JTree.java:511)
at usermanagementconsole.gui.GuiMenuTree.initTree(GuiMenuTree.java:44)
at usermanagementconsole.gui.GuiMenuTree.main(GuiMenuTree.java:51)
----------------------------------------------------------------------------------------------

i know little about JTree, so any suggestion will be appreciated, thx. Below is my code :
//here, the datas from tables are created
package usermanagementconsole.gui.data;

import usermanagementconsole.database.OracleSQL;
import java.sql.*;
import java.util.Hashtable;
import java.util.Vector;
/**
 *
 * @author dev60cgi
 */
public class TreeData extends OracleSQL {
    
    private String appcode, apptablename, menutablename;
    private int appid;
    /** Creates a new instance of TreeData */
    public TreeData(String Appcode) {      
        appcode = Appcode;
    }
    
    public void setAppTable(String Apptablename, String Menutablename) {
        apptablename = Apptablename;
        menutablename = Menutablename;
    }
    
    private void setAppID() {
        try {
            Statement stmt = oraConnection.createStatement();            
            String sql = "select app_id from "+apptablename+" where app_code = '"+appcode+"'";
            ResultSet rst = stmt.executeQuery(sql);
            while(rst.next()) {
                appid = rst.getInt(1);                
            }
            rst.close();
        }
        catch(SQLException sqx) {
            sqx.printStackTrace();
            appid = 0;            
        }
    }
    
    public boolean initTreeData() {
        boolean isExecuted = executeProcedure("populate_menu_data", appid);
        return isExecuted;
    }
    
    public String[] getChild(String parent) {
        Vector rowdata = new Vector();
        try {
            Statement stmt = oraConnection.createStatement();
            String sql = "select levels, menu_id from "+menutablename+" where upper(menu_name) = upper('"+parent+"')";
            ResultSet rst = stmt.executeQuery(sql);
            while(rst.next()) {
                int levels = rst.getInt(1)+1;
                int menuid = rst.getInt(2);
                String sqlchild = "select menu_name from "+menutablename+" where levels="+levels+" and menu_parent="+menuid;
                ResultSet rstchild = stmt.executeQuery(sqlchild);
                while(rstchild.next()) {
                    rowdata.addElement(rstchild.getString(1));
                }
            }
            stmt.close();
        }
        catch(SQLException sqx) {
            sqx.printStackTrace();
        }
        return getStringData(rowdata);
    }
    
    public int getChildCount(String parent) {
        int rowcount = 0;
        try {
            Statement stmt = oraConnection.createStatement();
            String sql = "select levels, menu_id from "+menutablename+" where upper(menu_name) = upper('"+parent+"')";
            ResultSet rst = stmt.executeQuery(sql);
            while(rst.next()) {
                int levels = rst.getInt(1)+1;
                int menuid = rst.getInt(2);
                String sqlchild = "select count(menu_name) from "+menutablename+" where levels="+levels+" and menu_parent="+menuid;
                ResultSet rstchild = stmt.executeQuery(sqlchild);
                while(rstchild.next()) {
                    rowcount = rstchild.getInt(1);
                }
            }
            stmt.close();
        }
        catch(SQLException sqx) {
            sqx.printStackTrace();
        }
        return rowcount;        
    }
    
    public boolean isLeaf(String menuname) {
        boolean isleaf = false;
        try {
            Statement stmt = oraConnection.createStatement();
            String sql = "select menu_type from "+menutablename+" where menu_name = '"+menuname+"'";
            ResultSet rst = stmt.executeQuery(sql);
            while(rst.next()) {
                int menutype = rst.getInt(1);
                if (menutype==2) {
                    isleaf = true;
                }
                else {
                    isleaf = false;
                }
            }
        }
        catch(SQLException sqx) {
            sqx.printStackTrace();
        }
        return isleaf;
    }
    private String[] getStringData(Vector data) {
        int rowcnt = data.size();
        String[] strdata = new String[rowcnt];
        for (int i=0;i<rowcnt;i++) {
            strdata[i] = data.elementAt(i).toString();
        }
        return strdata;
    }  
}

//Here, data model for JTree
package usermanagementconsole.gui.data;

import com.sun.java.swing.*;
import java.io.Serializable;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import javax.swing.tree.TreePath;

public class TreeDataModel extends DefaultTreeModel implements Serializable {

    TreeNode root;
    TreeData treedata;
    public TreeDataModel(TreeNode node) {        
        super(node);
        root = node;
        treedata = new TreeData("BO");
        treedata.setAppTable("TVR_JV_APP","TVR_JV_MENU_TEMP");
        treedata.initTreeData();
    }

    public Object getRoot() {
        return  root;
    }

    public Object getChild( Object parent, int index ) {
        String[] children = treedata.getChild((String)parent);
        return ( children[index] );
    }

    public int getChildCount( Object parent ) {
        int childcount = treedata.getChildCount((String)parent);
        return childcount;
    }

    public boolean isLeaf( Object node ) {
        return treedata.isLeaf((String)node);
    }

    public void valueForPathChanged( TreePath path, Object newValue ) {
        
    }

    public int getIndexOfChild( Object parent, Object child ) {     
        String[] children = treedata.getChild((String)parent);
        int result = -1;
        for ( int i = 0; i < children.length; ++i ) {
            if ( child.toString().equals( children[i] ) ) {
                result = i;
                break;
            }
        }        
        return result;
    }
    
}

//And then, create GUI to show JTree
package usermanagementconsole.gui;

import usermanagementconsole.database.*;
import usermanagementconsole.gui.data.TreeData;
import usermanagementconsole.gui.data.TreeDataModel;
import javax.swing.JFrame;
import javax.swing.plaf.*;
import javax.swing.tree.*;
import javax.swing.JTree;
import java.awt.BorderLayout;
import java.util.Hashtable;
/**
 *
 * @author dev60cgi
 */
public class GuiMenuTree extends JFrame {
    
    JTree tree;
    /** Creates a new instance of GuiMenuTree */
    public GuiMenuTree() {
        super("Verifikasi dan Audit");
        setSize(200, 150);    
    }
    
    public void initTree() {
        DefaultMutableTreeNode root = new DefaultMutableTreeNode("User Management Console");
        TreeDataModel model = new TreeDataModel(root);
        tree = new JTree(model);
        tree.putClientProperty("JTree.lineStyle", "Angled");
        getContentPane().add(tree, BorderLayout.CENTER);        
    }
    
    public static void main (String ar[]) {
        GuiMenuTree tt = new GuiMenuTree();
        tt.initTree();
        tt.setVisible(true);        
    }

}
plis help
843805
finally i found my own solution, fuihh....

for anyone looking for the solution, tutorial from sun will give you the light :D
843805
Hi,
Please can anyone help me with the code for dynamically displaying queried data from an oracle table in JTree. The table has around 3 fields and over 4000 records and is frequently updated with new records.

Need it urgently!!!

Thanks,
Priya Jeypal
843805
>
Need it urgently!!!
Shoot, I'm going out for lunch now, and I guess it will be too late to help when I get back. Oh well, hopefully someone else will be available.
1 - 4
Locked Post
New comments cannot be posted to this locked post.

Post Details

Locked on May 15 2006
Added on Dec 5 2005
4 comments
2,514 views