Java JTree create

Description

Java JTree create

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;

class Demo extends JPanel {

   public Demo() {
      JTree tree;/*from  w  w  w  .j a v  a  2  s .  c om*/
      JLabel jlab;
      // Create top node of tree.
      DefaultMutableTreeNode top = new DefaultMutableTreeNode("Options");

      // Create subtree of "A".
      DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
      top.add(a);
      DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
      a.add(a1);
      DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
      a.add(a2);

      // Create subtree of "B".
      DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
      top.add(b);
      DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
      b.add(b1);
      DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
      b.add(b2);
      DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");
      b.add(b3);

      // Create the tree.
      tree = new JTree(top);

      // Add the tree to a scroll pane.
      JScrollPane jsp = new JScrollPane(tree);

      // Add the scroll pane to the content pane.
      add(jsp);

      // Add the label to the content pane.
      jlab = new JLabel();
      add(jlab, BorderLayout.SOUTH);

      // Handle tree selection events.
      tree.addTreeSelectionListener(new TreeSelectionListener() {
         public void valueChanged(TreeSelectionEvent tse) {
            jlab.setText("Selection is " + tse.getPath());
         }
      });
   }
}

public class Main {
   public static void main(String[] args) {
      Demo panel = new Demo();

      JFrame application = new JFrame();

      application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

      application.add(panel);
      application.setSize(250, 250);
      application.setVisible(true);
   }
}



PreviousNext

Related