source file name: TreeDemo.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.tree.*;
class TreeDemo extends JFrame
{
JTextField txt;
public TreeDemo()
{
setLayout(null);
JLabel lb=new JLabel(" Structure of DBJ College");
txt=new JTextField(100);
DefaultMutableTreeNode root=new DefaultMutableTreeNode("DBJ College");
DefaultMutableTreeNode a=new DefaultMutableTreeNode("Arts");
DefaultMutableTreeNode c=new DefaultMutableTreeNode("Com.");
DefaultMutableTreeNode s=new DefaultMutableTreeNode("Sci.");
DefaultMutableTreeNode bsc=new DefaultMutableTreeNode("BSc");
DefaultMutableTreeNode cs=new DefaultMutableTreeNode("CS");
DefaultMutableTreeNode it=new DefaultMutableTreeNode("IT");
DefaultMutableTreeNode fy=new DefaultMutableTreeNode("FYCS");
DefaultMutableTreeNode sy=new DefaultMutableTreeNode("SYCS");
DefaultMutableTreeNode ty=new DefaultMutableTreeNode("TYCS");
DefaultMutableTreeNode p1=new DefaultMutableTreeNode("Algorithm");
DefaultMutableTreeNode p2=new DefaultMutableTreeNode("Core Java");
DefaultMutableTreeNode p3=new DefaultMutableTreeNode("Advanced Java");
sy.add(p1);
sy.add(p2);
sy.add(p3);
cs.add(fy);cs.add(sy);cs.add(ty);
s.add(bsc);s.add(cs);s.add(it);
root.add(a);root.add(c);root.add(s);
JTree tr=new JTree(root);
JPanel panel = new JPanel();
lb.setBounds(50,50,150,20);
JScrollPane sp=new JScrollPane(tr);
sp.setBounds(50,90,250,200);
txt.setBounds(50,350,300,20);
add(lb);add(sp);add(txt);
tr.addMouseListener(new MouseAdapter()
{
public void mousePressed(MouseEvent me)
{
TreePath tp=tr.getPathForLocation(me.getX(),me.getY());
txt.setText("Path: "+tp);
System.out.println("Tree selected path: "+tp);
}
});
}
public static void main(String as[])
{
TreeDemo f=new TreeDemo();
f.setTitle("Tree program");
f.setSize(300,300);
f.setVisible(true);
}
}
Output:
0 Comments
Post a Comment