JavaRanch » Java Forums »
Java »
Swing / AWT / SWT
| Author |
I am lost , Help Me Please ...JTree
|
Kinu Kanwar
Ranch Hand
Joined: Apr 19, 2005
Posts: 33
|
|
import javax.xml.parsers.*; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.tree.* ; public class XTreeTester1 extends JFrame { private JScrollPane jScroll; private WindowListener winClosing; protected DefaultMutableTreeNode rootNode; protected DefaultTreeModel treeModel; protected JTree tree; public XTreeTester1( String title) { super( title ); setSize( 500 , 500) ; rootNode = new DefaultMutableTreeNode("Root Node") ; treeModel = new DefaultTreeModel(rootNode); tree = new JTree(treeModel); DefaultMutableTreeNode p1 = addObject(null, new DefaultMutableTreeNode("Parent 1") , false); // if null then root is father DefaultMutableTreeNode p2 = addObject(null, new DefaultMutableTreeNode("Parent 2") , false); addObject(p1, new DefaultMutableTreeNode("Child 1") , false); addObject(p1, new DefaultMutableTreeNode("Child 2") , false ); addObject(p2, new DefaultMutableTreeNode("Child 3") , false); addObject(p2, new DefaultMutableTreeNode("Child 4") , false); jScroll = new JScrollPane(); jScroll.getViewport().add( tree ); getContentPane().add( jScroll, BorderLayout.CENTER ); validate(); setVisible(true); winClosing = new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }; addWindowListener(winClosing); } //END Of Constructor public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, DefaultMutableTreeNode child, boolean shouldBeVisible) { treeModel.insertNodeInto(child, parent, parent.getChildCount()); return child; } public static void main( String[] args ) { XTreeTester1 example2 = new XTreeTester1( "Example - 2" ); } } //end XTreeTester The above code works fine bu tI ahve one issue ... When you call addObject() then you pass parent and child .... If Parent has not been already added to Tree then child does not get add ... I am reading from text file to create JTree so its possible that child node may be there first like xxx is child of yyy yyy is child of zzz zzz yyy xxx would be tree structure for above text But I cant add xxx in JTree unless yyy has been added .... Its logical but any solution for my case ??? .... When I want to add child first in tree .. Please dont ask me abt sorting of text file .... My data is String Id[] = "0" , "1" , "2" , "3" , "4" , "5" , "6" , "7" , "8" String ParentId[] = "-1" , "0" , "0" , "1" , "1" , "3" ,"3" , "2" , "2" I want to draw tree for above structure ..Any order is possible for Id array .... Kinu
|
 |
Craig Wood
Ranch Hand
Joined: Jan 14, 2004
Posts: 1535
|
|
Written in j2se 1.5 and uses autoboxing and generics. To compile in earlier versions comment/uncomment the indicated lines.
|
 |
 |
|
|
subject: I am lost , Help Me Please ...JTree
|
|
|
|