Solution:NIIT/GNIIT Sonugiri0032@gmail.com

Wednesday, January 06, 2016

Tree Data Structure in Java | Tree Data Structure tutorials | Tree Data Structure tutorials with example | Tree Data Structure questions and answers |

Tree Data Structure in Java | Tree Data Structure tutorials | Tree Data Structure tutorials with example | Tree Data Structure questions and answers |

Source Code 

package TempClass;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;

public class TestTree extends JFrame {

  JTree myTree;

  DefaultTreeModel myModel;

  public TestTree() {
    super("Tree Test Example");
    setSize(400, 300);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
  }

  public void init() {
    DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
    DefaultMutableTreeNode subroot = new DefaultMutableTreeNode("SubRoot");
    DefaultMutableTreeNode leaf1 = new DefaultMutableTreeNode("Leaf 1");
    DefaultMutableTreeNode leaf2 = new DefaultMutableTreeNode("Leaf 2");

    myModel = new DefaultTreeModel(root);
    myTree = new JTree(myModel);

    myModel.insertNodeInto(subroot, root, 0);
    
    subroot.add(leaf1);
    root.add(leaf2);

    getContentPane().add(myTree, BorderLayout.CENTER);
    expandAll(myTree);
  }

  public static void main(String args[]) {
    TestTree myTestTree = new TestTree();
    myTestTree.init();
    myTestTree.setVisible(true);
    
  }
  // to expend all nodes of a Tree
  public void expandAll(JTree tree) {
    int row = 0;
    while (row < tree.getRowCount()) {
      tree.expandRow(row);
      row++;
      }
    }
}

Output of the Progam

tree in data structure
Share:

0 comments:

GNIITSOLUTION GNIIT SOLUTION. Powered by Blogger.

Translate

Blog Archive

Unordered List