Results 1 to 11 of 11
  1. #1
    grahamb314 is offline Member
    Join Date
    Nov 2008
    Posts
    13
    Rep Power
    0

    Unhappy JTree - Save and load from an array?

    Hi!

    I'm trying to allow users to create a hierarchy of folders from a Java gui page.
    I found the best representational method of showing a hierarchy of folders to a user with a gui is with a JTree?

    I can create a JTree, but i need the user to be able to add/remove and modify nodes on the JTree to reflect the folder structure they want to create.

    This JTree then needs to be saved (in a database) so that on another day, this folder structure can be edited by the user. So I need to populate a JTree from the database values already saved and display the editable JTree to the user for further editing.
    Then on another day, the user will actually want to create the folder structure based on the JTree/database values. - I can do this directly from the database without having to display the JTree again.

    I assume I can create an array from the JTree and store the values of the array in the database, then use those values in the database later to populate the array(s) and then build the JTree again from it. - Then to make the folder structure, just use the values from the database?

    I have spent a whole day on this, and I came across this example:
    Using Swing Components: Examples (The Java™ Tutorials > Creating a GUI with JFC/Swing > Using Swing Components)

    from here: How to Use Trees (The Java™ Tutorials > Creating a GUI With JFC/Swing > Using Swing Components) (See: Dynamically Changing a Tree)

    ^ This is great because it allows the user to edit the tree.

    Basically, I can write methods to write something to the database, retrieve it back and actually create the folders, but I am having no hope at all in dynamically saving or loading a JTree from say an array(from the database).

    I have no preference on if i use arrays or other data structure, as long as its not too difficult to loop them and put the values in the database.

    If anyone can help, that really would be amazing.
    (Attached a picture to help explain)

    Thanks!
    Attached Thumbnails Attached Thumbnails JTree - Save and load from an array?-example.jpg  

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default

    Might be overkill because I'm not fully sure what sort of data you have and how complex the relations need to be, but have a look at the following link:
    MySQL :: Managing Hierarchical Data in MySQL
    One of the better articles I've found describing methods for storing trees in a relational database.

  3. #3
    grahamb314 is offline Member
    Join Date
    Nov 2008
    Posts
    13
    Rep Power
    0

    Default

    Hi doWhile

    I think overkill is probably right :)

    There are only going to be approx 3 levels of directories, with maybe 2-3 folders in each.

    Storing the information in a database will be the easy bit, my issue is more with the Java, ie. Loading and creating a JTree from a datastructure such as an array (or several)
    I was thinking along the lines of having an array of node names and an array of structure:

    node_names[] =
    [0] = "Folder 1"
    [1] = "Folder 2"
    [2] = "Folder 3"
    node_structure[]=
    [0] = 0 // Means that node 0 will have parent root
    [1] = 0 // Means that node 1 will have a parent root
    [2] = 1 // Means that node 2 will have a parent node 1 (Which is called "Folder 3")

    Attached an image to relate to this example

    Basically I need a way to populate a JTree from a data structure and to create a data structure (arrays maybe) from a JTree. Then maknig rows in a database from those data structures should be easy for me
    Attached Thumbnails Attached Thumbnails JTree - Save and load from an array?-example2.png  

  4. #4
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default

    The JTree is already a data structure (Tree), so the first option in the link above would be incredibly easy to implement. Create a table in the DB that contains unique ids, a parent id (referencing the unique ID of the parent), and other info (perhaps a group number for each JTree you want to create). To input the data, just iterate through the JTree nodes and their children, placing each entry in the DB with the id of the parent. To read the JTree, just do the opposite: retrieve all entries (of a given group if necessary), then loop over them creating Nodes for the tree and using the parent ID to link up the nodes. To add just add another record with the correct info. To delete, just delete the node record and its descendents in the table. Now that I think about it, its probably not overkill.
    Last edited by doWhile; 01-27-2011 at 08:17 PM.

  5. #5
    grahamb314 is offline Member
    Join Date
    Nov 2008
    Posts
    13
    Rep Power
    0

    Default

    Thanks for your help so far.

    Based on what you have explained, I have come up with the following after some intense googleing!
    There are two methods that are used for tree traversal (I can adapt these to instead of printing the nodes, but to put them in the database)

    I am though going to have a problem creating a tree based on whats the in database.
    Would you be able to reverse the two short methods below to populate a tree for me? - Or point me to an example?

    Thanks again.

    Java Code:
    import java.awt.event.WindowAdapter;
    import java.awt.event.WindowEvent;
    import javax.swing.*;
    import javax.swing.tree.DefaultMutableTreeNode;
    import javax.swing.tree.TreeModel;
    
    public class SimpleJTreeExample extends JFrame {
    
    	public static void main( String[] argv ) {
    		SimpleJTreeExample myExample = new SimpleJTreeExample( "Simple JTree Example" );
    	}
    
    	public SimpleJTreeExample( String title ) {
    		super( title );
    		setSize( 150, 150 );
    		addWindowListener( new WindowAdapter() {
    			public void windowClosing( WindowEvent we ) {
    				dispose();
    				System.exit( 0 );
    			}
    		} );
    		init();
    		pack();
    		setVisible( true );
    	}
    
    	private void init() {
    		DefaultMutableTreeNode root = new DefaultMutableTreeNode( "Calendar" );
    		DefaultMutableTreeNode months = new DefaultMutableTreeNode( "Months" );
    		root.add( months );
    		String monthLabels[] = {"January", "February", "March", "April", "May",
    				"June", "July", "August", "September", "October", "November", "December"};
    		for( int i = 0; i < monthLabels.length; i++ )
    			months.add( new DefaultMutableTreeNode( monthLabels[i] ) );
    		DefaultMutableTreeNode weeks = new DefaultMutableTreeNode( "Weeks" );
    		root.add( weeks );
    		String weekLabels[] = {"Monday", "Tuesday", "Wednesday", "Thursday",
    				"Friday", "Saturday", "Sunday"};
    		for( int i = 0; i < weekLabels.length; i++ )
    			weeks.add( new DefaultMutableTreeNode( weekLabels[i] ) );
    		JTree the_tree = new JTree( root );
    		JScrollPane js = new JScrollPane( the_tree );
    		getContentPane().add( js );
    		traverse(the_tree);
    	}
    	public void traverse(JTree tree) { 
    		TreeModel model = tree.getModel(); 
    		if (model != null) { 
    			Object root = model.getRoot(); 
    			System.out.println(root.toString()); 
    			walk(model,root); 
    		} 
    		else 
    			System.out.println("Tree is empty."); 
    	} 
    
    	protected void walk(TreeModel model, Object o){ 
    		int cc; 
    		cc = model.getChildCount(o); 
    		for( int i=0; i < cc; i++) { 
    			Object child = model.getChild(o, i ); 
    			if (model.isLeaf(child)) 
    				System.out.println("Leaf: "+i+" "+child.toString()); 
    			else { 
    				System.out.print("\n\rParent: "+i+" "+child.toString()+"\n\r"); 
    				walk(model,child ); 
    			} 
    		} 
    	} 
    }
    This outputs:
    Java Code:
    Calendar
    
    Parent: 0 Months
    
    Leaf: 0 January
    Leaf: 1 February
    Leaf: 2 March
    Leaf: 3 April
    Leaf: 4 May
    Leaf: 5 June
    Leaf: 6 July
    Leaf: 7 August
    Leaf: 8 September
    Leaf: 9 October
    Leaf: 10 November
    Leaf: 11 December
    
    
    Parent: 1 Weeks
    
    Leaf: 0 Monday
    Leaf: 1 Tuesday
    Leaf: 2 Wednesday
    Leaf: 3 Thursday
    Leaf: 4 Friday
    Leaf: 5 Saturday
    Leaf: 6 Sunday
    Which looks like:
    Attached Thumbnails Attached Thumbnails JTree - Save and load from an array?-example3.jpg  
    Last edited by grahamb314; 01-28-2011 at 09:12 PM.

  6. #6
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default

    I won't do it for you (and don't have an example to point to), but can kind of walk you through it....you can read in the data from a ResultSet and connect them using a Map...first read in each entry in the table into a new node object (you will have to design it so that you can retrieve the id and parent id of that node) and place those in a Map keyed by the id. Once read, iterate over the map, connecting each node with its parent physically using TreeNode's (you retrieve the parent from the Map). The node that does not have a parent is the root node, which you can then set as the root node of your JTree.

  7. #7
    grahamb314 is offline Member
    Join Date
    Nov 2008
    Posts
    13
    Rep Power
    0

    Default

    Thank you again for your help on this.

    Looping is something I cant get my head around!

    I think that all I need on the database side of things is 1 table like this? (From your suggestion) - Am I right? - (Attached image)

    This is what i understand from your suggestion

    Based on the above table layout, for each row in the table create a new node: (By looping the resultSet)
    Java Code:
    nodeArray[i] = new DefaultMutableTreeNode("node_name");
    Now I have loads of nodes in an array

    After this, I get confused about this etc.
    (you will have to design it so that you can retrieve the id and parent id of that node)
    Would it be possible to loop through the resultSet and create all the nodes from there? - If so, could you possibly explain how that might be done?
    Attached Thumbnails Attached Thumbnails JTree - Save and load from an array?-example4.jpg  
    Last edited by grahamb314; 01-28-2011 at 10:54 PM.

  8. #8
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default

    I think that all I need on the database side of things is 1 table like this?
    That is up to you. If that is all the info you wish to capture, then yes.

    Would it be possible to loop through the resultSet and create all the nodes from there?
    Yes, but linking them would depend upon how you query and retrieve the data. The method I posted above is independent of those issues. Pseudo-code for the method I described above
    Java Code:
    Map<String, Node> idToNode = new HashMap<String, Node>();
    //create nodes from ResultSet
    while ( resultSet.next() ){
    Node node = //create node -contains info, parent id, and its own id from ResultSet
    //put node into idToNode, keyed with its id
    }
    //link together
    Iterator<String> it = idToNode.keySet().iterator();
    Node root = null;
    while ( it.hasNext() ){
        Node node = idToNode.get(it.next());
        Node parent = idToNode.get(node.getParentId());
        if ( parent == null ) {
            root = node;
        }else{
           parent.addChild(node);
        }
    }

  9. #9
    grahamb314 is offline Member
    Join Date
    Nov 2008
    Posts
    13
    Rep Power
    0

    Default

    I really appreciate you helping me with this.

    I think I can implement it, apart from this line in your pseudo code:

    Java Code:
    //put node into idToNode, keyed with its id
    I'll work on this tonight after your assistance with the above and then I'll post what I manage!

    Thanks once again!

  10. #10
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default

    My wording was a hint...the code I posted uses a Map, so I recommend reading the API to investigate how to use this class.

  11. #11
    michalss is offline Member
    Join Date
    Mar 2011
    Posts
    17
    Rep Power
    0

    Default

    I'm trying to archive exact the same thing here. Did you manage to solve it please ?

Similar Threads

  1. Save/Load ArrayList
    By chielt in forum New To Java
    Replies: 3
    Last Post: 05-08-2011, 06:12 PM
  2. Load and Save images
    By shakeel in forum Java 2D
    Replies: 13
    Last Post: 12-29-2010, 06:38 PM
  3. Arraylist Save and Load
    By frankycool in forum Advanced Java
    Replies: 1
    Last Post: 11-14-2009, 10:29 PM
  4. How to load a directory in JTree with Children(On expansion)
    By aneesahamedaa in forum AWT / Swing
    Replies: 0
    Last Post: 10-13-2008, 01:23 PM
  5. How to Save/Load Vector to/from file
    By Java Tip in forum java.lang
    Replies: 0
    Last Post: 04-14-2008, 08:37 PM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •