Java jtree basic tutorial and examples
In Java, a JTree is a basic GUI component used to display hierarchical data, such as a file system or a tree structure. Here's a basic example of how to create and use a JTree:
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample extends JFrame {
public TreeExample() {
super("JTree Example");
// Create the root node and add child nodes to it
DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
DefaultMutableTreeNode node1 = new DefaultMutableTreeNode("Node 1");
DefaultMutableTreeNode node2 = new DefaultMutableTreeNode("Node 2");
root.add(node1);
root.add(node2);
// Create the tree and add it to a scroll pane
JTree tree = new JTree(root);
JScrollPane scrollPane = new JScrollPane(tree);
// Add the scroll pane to a panel and add the panel to the frame
JPanel panel = new JPanel();
panel.add(scrollPane);
add(panel);
// Set the size, location and visibility of the frame
pack();
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}
}
In this example, we create a JTree by creating a DefaultMutableTreeNode to represent the root of the tree, and then adding child nodes to it. We then create the JTree using the root node and add it to a JScrollPane.
We add the JScrollPane to a JPanel and add the panel to the JFrame. When you run this example, a window will appear with a tree view of the nodes we created. You can expand and collapse the nodes by clicking on them.
