Oct 08

A JTree can be used for displaying trees in Swing. The data can be first loaded into a DefaultTreeModel (where is node is represented by a DefaultMutableTreeNode) for rendering by the JTree.


import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.TreeMap;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.MutableTreeNode;
import javax.swing.tree.TreeModel;


public class FolderTree
{
	public static void main(String[] args)
	{
		// Generate some test data
		// We'll use a Map which is keyed on folder name
		// With each folder name referencing a list of 
		// strings containing children names
		
		Random seed = new Random();
		Map<String, List<String>> folders = 
			new TreeMap<String, List<String>>();
		for (char c = 'A'; c<='G'; c++)
		{
			List<String> children = new ArrayList<String>();
			for (int i=0; i<seed.nextInt(3); i++)
			{
				children.add(Integer.toString(i));
			}
			folders.put(Character.toString(c), children);
		}
		
		// Now we create TreeModel and 
		// populate it with our test data
		
		DefaultMutableTreeNode root = 
			new DefaultMutableTreeNode("FOLDERS");
		TreeModel treeModel = new DefaultTreeModel(root, true);
		for (String folderName : folders.keySet())
		{
			// Create a node for the folder
			
			DefaultMutableTreeNode folder = 
				new DefaultMutableTreeNode(folderName, true);
			for (String childName : folders.get(folderName))
			{
				// Add child to the folder
				
				MutableTreeNode child = 
					new DefaultMutableTreeNode(childName, false);
				folder.add(child);
			}
			root.add(folder);
		}
		
		// Create a frame with JTree displaying our data
		
		JFrame frame = new JFrame("Folder Tree");
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		// Pass the previously create model to our tree 
		
		JTree tree = new JTree(treeModel);
		frame.add(new JScrollPane(tree));
		frame.pack();
		frame.setVisible(true);
	}
}


written by objects \\ tags: , ,


Leave a Reply

You must be logged in to post a comment.