In this section, you will learn how to add or insert a new node to the JTree component. The tree has root node and child of rood node. Sometimes, you need to insert the node, you must be insert your node to the JTree component.
Adding a Node to the JTree Component
In this section, you will learn how to add or insert a new node to the JTree component. The tree has root node and child of rood node. Sometimes, you need to insert the node, you must be insert your node to the JTree component.
Description of program:
The following program helps you in adding or inserting a new node to the JTree component. After running this program appears a graphical layout on the screen that has tree with root node and child of root node and one command button (Add Tree). When you will click this button appears an input box that takes a node name that have to be inserted in JTree. If the input box is empty or blank and click the "OK" button, After clicking the "OK" button no any node are added in tree and it will display a message "Node is not added in the tree" in message box. Again, if you will click the "Add Tree" command button, it provides an input box that takes node name and click the "OK" command button. After clicking the "OK" button the given node are added in tree and it will display a message "Node are added in the tree" in the message box. Finally, you will get added or inserted the given node in the JTree.
Description of code:
getModel():
This is the method that returns data model. This data model contains list of
items that displayed by the JList component.
getNextMatch(String prefix, int startIndex,
Position.Bias bias):
This is the method that returns the index of the next list element which is
started with the given prefix otherwise it will start with '1'. It takes the
following arguments:
prefix: This
is the string to test for matching in JTree component.
startIndex: This is an index to
start the search.
bias: This is the searching
direction either Position.Bias.Forward or Position.Bias.Backward.
Forward: This field indicates to bias toward the next character in model.
Backward: This field indicates to bias toward the previous character in model.
getLastPathComponent():
This is the method that returns the last component of tree path.
insertNodeInto(MutableTreeNode nNode,
MutableTreeNode node, int index):
This is the method that inserts a new child at specified location.
Here is the code of program:
import java.awt.event.*;
|
Output of program:
Before adding a node:
Click the "Add Tree" command button:
Click the "OK" command button:
Click the "OK" command button:
Again click the "Add Tree" command button:
Click the "Ok" command button:
Adding a node: