Editable JTree

In this section, you will learn to make JTree editable nodes.

Editable JTree Nodes 


In this section, you will learn  to make JTree editable nodes. For example. . If you want to edit the  name of a  tree node then the following program will  help you a lot.

Program Description:

This program constructs a JTree that contains editable nodes. Firstly, it defines a class  "JTreeEditable".  Here we have used the init() method to create the  nodes  (Root, open, close, save, save as, and exit) of the tree. These nodes are added in a JTree object and we set the editable mode to " true " through the setEditable() method. The init() method adds these components to the JFrame. When you want to edit these components, just double click them and rename them..

This method takes a  boolean value that is either a 'true' or a  'false'. When you enter true it becomes editable.

Here is the code of this program:

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

public class JTreeEditable extends JFrame {
  DefaultTreeModel treeModel;
  public JTreeEditable() {
  super("Editable Tree Frame");
  public void init(){
  DefaultMutableTreeNode root = new DefaultMutableTreeNode("Root");
  DefaultMutableTreeNode file = new DefaultMutableTreeNode("File");
  DefaultMutableTreeNode open = new DefaultMutableTreeNode("Open")
  DefaultMutableTreeNode save = new DefaultMutableTreeNode("Save")
  DefaultMutableTreeNode saveas = new DefaultMutableTreeNode("Save As")
  DefaultMutableTreeNode exit = new DefaultMutableTreeNode("Exit")
  treeModel = new DefaultTreeModel(root);
  JTree tree = new JTree(treeModel);
  treeModel.insertNodeInto(file,root, 0);
  getContentPane().add(tree, BorderLayout.CENTER);
  public static void main(String args[]) {
  JTreeEditable st = new JTreeEditable();

Download this program.

Output this program:


Share on Google+Share on Google+

Editable JTree

Posted on: May 30, 2007 If you enjoyed this post then why not add us on Google+? Add us to your Circles



Discuss: Editable JTree  

Post your Comment

Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image