I thought "JTree. setRootVisible(false)" would hide the root yet display its children, but it doesn't. I've even tried to expand its children but nothing shows when I hide the root.

Here's the code if you need to see it.

DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("Root");
JTree projectTree = new JTree(rootNode);
 
 
/** add some dummy data */
DefaultMutableTreeNode prNode = new DefaultMutableTreeNode("Euphoria"); //project
DefaultMutableTreeNode pNode = new DefaultMutableTreeNode("euphoria"); //package
pNode.add(new DefaultMutableTreeNode("AutoscrollTextArea.java"));
DefaultMutableTreeNode p2Node = new DefaultMutableTreeNode("euphoria.utils");
p2Node.add(new DefaultMutableTreeNode("Timer.java"));        
pNode.add(p2Node);
prNode.add(pNode);        
rootNode.add(prNode);
 
 
projectTree.setRootVisible(false);

Here you go. Dynamically add nodes to JTree while keeping the root node hidden. I give 10 points to the genius who designed the JTree (and friends) API.

private JTree createJTree() {
	
	/* Create JTree */
	
	JTree jTree = new JTree();
	jTree.setRootVisible( false );

	DefaultMutableTreeNode rootNode = new DefaultMutableTreeNode("root node, should be invisible");
	DefaultTreeModel defaultTreeModel = new DefaultTreeModel( rootNode );
	
	jTree.setModel( defaultTreeModel );
	
	
	/* Add nodes to it */
	
	DefaultMutableTreeNode parentNode; 
	DefaultMutableTreeNode node;
	
	
	parentNode = (DefaultMutableTreeNode) defaultTreeModel.getRoot(); 
	node = new DefaultMutableTreeNode( "node 1" );
	addNodeToDefaultTreeModel( defaultTreeModel, parentNode, node );
	
	parentNode = node; 
	node = new DefaultMutableTreeNode( "node 2" );
	addNodeToDefaultTreeModel( defaultTreeModel, parentNode, node );
	
	parentNode = (DefaultMutableTreeNode) defaultTreeModel.getRoot(); 
	node = new DefaultMutableTreeNode( "node 3" );
	addNodeToDefaultTreeModel( defaultTreeModel, parentNode, node );
	
	parentNode = node; 
	node = new DefaultMutableTreeNode( "node 4" );
	addNodeToDefaultTreeModel( defaultTreeModel, parentNode, node );
	
	return jTree;
}


private static void addNodeToDefaultTreeModel( DefaultTreeModel treeModel, DefaultMutableTreeNode parentNode, DefaultMutableTreeNode node ) {
	
	treeModel.insertNodeInto(  node, parentNode, parentNode.getChildCount()  );
	
	if (  parentNode == treeModel.getRoot()  ) {
		treeModel.nodeStructureChanged(  (TreeNode) treeModel.getRoot()  );
	}
}

To hide the root node and still make its children expandable (i.e. appear like multiple root nodes) after tree.setRootVisible(false) call tree.setShowsRootHandles(true).

Try this:

jtree.expandRow(0)
jtree.setRootVisible(false)

Expand the root and make it invisible. If you just make it invisible the user has no chance:-) There is a certain (silly) logic to it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.