Sunday, 29 June 2014

Program For JTreedemo In Java------------


import javax.swing.*;
import java.awt.*;
import javax.swing.tree.*;
import java.awt.event.*;

/*<applet code="JTreedemo" width=400 height=200></applet>*/

public class JTreedemo extends JApplet
{
JTree tr;
JTextField f;

public void init()
{
Container c=getContentPane();



c.setLayout(new BorderLayout());

DefaultMutableTreeNode top=new DefaultMutableTreeNode("select");

DefaultMutableTreeNode a=new DefaultMutableTreeNode("colors");
top.add(a);

DefaultMutableTreeNode a1=new DefaultMutableTreeNode("red");
a.add(a1);
DefaultMutableTreeNode a2=new DefaultMutableTreeNode("Green");
a.add(a2);

DefaultMutableTreeNode b=new DefaultMutableTreeNode("fruits");
top.add(b);

DefaultMutableTreeNode b1=new DefaultMutableTreeNode("mango");
b.add(b1);
DefaultMutableTreeNode b2=new DefaultMutableTreeNode("apple");
b.add(b2);

DefaultMutableTreeNode c3=new DefaultMutableTreeNode("names");
top.add(c3);

DefaultMutableTreeNode c1=new DefaultMutableTreeNode("abc");
c3.add(c1);
DefaultMutableTreeNode c2=new DefaultMutableTreeNode("xyz");
c3.add(c2);
DefaultMutableTreeNode c4=new DefaultMutableTreeNode("pqr");
c3.add(c4);
DefaultMutableTreeNode c5=new DefaultMutableTreeNode("efg");
c3.add(c5);

tr=new JTree(top);

int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
JScrollPane jsp=new JScrollPane(tr,v,h);

c.add(jsp,BorderLayout.CENTER);

 f=new JTextField(20);
c.add(f,BorderLayout.SOUTH);


tr.addMouseListener(new MouseAdapter()
{
public void mouseClicked(MouseEvent me)
{
doMouseClicked(me);
}
});
}

 void doMouseClicked(MouseEvent me)
{
TreePath tp=tr.getPathForLocation(me.getX(),me.getY());
if(tp!=null)
f.setText(tp.toString());
else
f.setText("");
}


}




No comments:

Post a Comment