JTree Java Swing Component Demo

11/12/2011 code-examplejavajava-swing

# Summary

This is an example displaying the usage of JTree Swing Component, how the default mutable nodes work, we can get their path using the TreePath class and hence we can form an heirarchical tree which on click displays the path of the node being selected.

# Code

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package swingdemo;

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

/**
 *
 * @author Rohan
 */
public class JTreeDemo extends JApplet {

    JTree tree;
    JTextField jtf;

    @Override
    public void init() {
        Container cp = getContentPane();
        cp.setLayout(new BorderLayout());
        DefaultMutableTreeNode top = new DefaultMutableTreeNode("Option");
        DefaultMutableTreeNode a = new DefaultMutableTreeNode("A");
        DefaultMutableTreeNode a1 = new DefaultMutableTreeNode("A1");
        DefaultMutableTreeNode a2 = new DefaultMutableTreeNode("A2");
        DefaultMutableTreeNode b = new DefaultMutableTreeNode("B");
        DefaultMutableTreeNode b1 = new DefaultMutableTreeNode("B1");
        DefaultMutableTreeNode b2 = new DefaultMutableTreeNode("B2");
        DefaultMutableTreeNode b3 = new DefaultMutableTreeNode("B3");

        top.add(a);
        top.add(b);
        a.add(a1);
        a.add(a2);
        b.add(b1);
        b.add(b2);
        b.add(b3);

        tree = new JTree(top);

        int h = ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED;
        int v = ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;

        JScrollPane jsp = new JScrollPane(tree, v, h);
        cp.add(jsp, BorderLayout.CENTER);

        jtf = new JTextField(20);
        cp.add(jtf, BorderLayout.SOUTH);
        tree.addMouseListener(new MouseAdapter() {

            public void mouseClicked(MouseEvent me) {
                doMouseClick(me);
            }
        });
    }

    public void doMouseClick(MouseEvent me) {
        TreePath tp = tree.getPathForLocation(me.getX(), me.getY());
        if (tp != null) {
            jtf.setText(tp.toString());
        } else {
            jtf.setText("");
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69