/* Derived from JTree1 1) removed the popupmenu stuff 2) Get rid of the default content (sports, colors...) > Is there a way to create a JTree with a null root node and no elements > without Swing adding the colors, sports and food nodes automatically ? Provide your own empty model, and check JTree's API documentation for hiding the root node 3) Removed unused methods : - addObject(Object), addObject(DefaultMutableTreeNode,Object) - showSelected() */ import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.tree.*; public class JTree0 extends JTree { DefaultMutableTreeNode root; DefaultTreeModel treeModel; public JTree0( DefaultMutableTreeNode root ) { super( root ); this.root = root; // Really useful ? treeModel = new DefaultTreeModel(root); this.setModel( treeModel ); addMouseListener( new MouseAdapter() { public void mousePressed(MouseEvent e) { int r = getRowForLocation(e.getX(),e.getY()); System.err.println("mousePressed() b=" + e.getButton() + " r=" + r ); } } ); } public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, Object child, boolean shouldBeVisible) { DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child); if (parent == null) { parent = root; } // Invoke this on the TreeModel, and NOT DefaultMutableTreeNode treeModel.insertNodeInto( childNode, parent, parent.getChildCount() ); if (shouldBeVisible) { scrollPathToVisible(new TreePath(childNode.getPath())); } return childNode; } void populateTree() { String p1Name = new String("Parent 1"); String p2Name = new String("Parent 2"); String c1Name = new String("Child 1"); String c2Name = new String("Child 2"); DefaultMutableTreeNode p1, p2; p1 = addObject(null, p1Name, true ); // added 3rd argt 'true' to make visible p2 = addObject(null, p2Name, true ); addObject(p1, c1Name, true ); addObject(p1, c2Name, true ); /* addObject(p2, c1Name, true ); addObject(p2, c2Name, true ); */ } public static void main( String a[] ) { JFrame f = new JFrame("JTree0"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.setSize(400,400); DefaultMutableTreeNode r = new DefaultMutableTreeNode("TreeT"); JTree0 t = new JTree0( r ); t.populateTree(); f.getContentPane().add(t); f.setVisible(true); } }