Home | Ajax | BioInformatics | Dojo | EAI | EJB | Hibernate | J2ME | Java | Java Glossary | Java Servlets | JavaScript | Jboss | JDBC | JDO | Jmeter | JSF | JSP | JUnit | Maven | MySQL | Spring Framework | SQL | Struts | Technology | WAP | Web Services | XML


 
  
 
Programming Tutorials: Ajax | Articles | JSP | Bioinformatics | Database | Free Books | Hibernate | J2EE | J2ME | Java | JavaScript | JDBC | JMS | Linux | MS Technology | PHP | RMI | Web-Services | Servlets | Struts | UML
 

 
Facing Programming Problem?
Ask Questions?, Browse Latest Questions, Question-Answer Guidelines
Java
  JDO Tutorials
  EAI Articles
  Struts Tutorials
  Java Tutorials
  Java Certification
  Java Applet
Questions
Comments

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.*;
import javax.swing.*;
import javax.swing.tree.*;
import javax.swing.text.*;

public class AddNodes{
  public static DefaultTreeModel model;
  public static TreePath path;
  public static JTree tree;
  public static DefaultMutableTreeNode nNode;
  public static MutableTreeNode node;
  String nodeName;
  public static void main(String[] args) {
    JFrame frame = new JFrame("Adding a Node to a JTree Component!");
    JPanel panel = new JPanel();
    DefaultMutableTreeNode myComputer = new DefaultMutableTreeNode("My Computer");
    DefaultMutableTreeNode c = new DefaultMutableTreeNode("Local Disk(C:)");
    DefaultMutableTreeNode vinod = new DefaultMutableTreeNode("Vinod");
    DefaultMutableTreeNode swing = new DefaultMutableTreeNode("Swing");
    DefaultMutableTreeNode tr = new DefaultMutableTreeNode("Tree");
    DefaultMutableTreeNode a = new DefaultMutableTreeNode("3½ Floppy(A:)");
    DefaultMutableTreeNode e = new DefaultMutableTreeNode("New Volume(E:)");
    c.add(vinod);
    vinod.add(swing);
    swing.add(tr);
    myComputer.add(c);
    myComputer.add(a);
    myComputer.add(e);
    tree = new JTree(myComputer);
    JButton button = new JButton("Add Tree");
    button.addActionListener(new ActionListener(){
      public void actionPerformed(ActionEvent ae){
        model = (DefaultTreeModel)tree.getModel();
        String nodeName = JOptionPane.showInputDialog(null, "Enter the node name:");
        if(nodeName.equals("")){
          JOptionPane.showMessageDialog(null, "Node is not added in the tree!");
        }
        else{
      //    create a new node
          nNode = new DefaultMutableTreeNode(nodeName);
          path = tree.getNextMatch("M"0, Position.Bias.Forward);
          node = (MutableTreeNode)path.getLastPathComponent();
          model.insertNodeInto(nNode, node, node.getChildCount());
          JOptionPane.showMessageDialog(null, "Node are added in the tree!");
        }
      }
    });
    panel.add(tree);
    panel.add(button);
    frame.add(panel);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setUndecorated(true);
    frame.getRootPane().setWindowDecorationStyle(JRootPane.PLAIN_DIALOG);
    frame.setSize(200,200);
    frame.setVisible(true);
  }
}

Download this example

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:

                         

Leave your comment:

Name:

Email:

URL:

Title:

Comments:


Enter Code:

Audio Version
Reload Image
 

Note: Emails will not be visible or used in any way, and are not required. Please keep comments relevant. Any content deemed inappropriate or offensive may be edited and/or deleted.

No HTML code is allowed. Line breaks will be converted automatically. URLs will be auto-linked. Please use BBCode to format your text.

Add This Tutorial To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 

Current Comments

2 comments so far (
post your own) View All Comments Latest 10 Comments:


String result=JOptionPane.showInputDialog(fhome,"enter the booknumber:\n"+" ","issue the book",JOptionPane.PLAIN_MESSAGE);

this is my inputbox.

String q2="update tblib set status='issued'where booknumber="

and this is my database query
my problem is how to compare the result with booknumber in my table.here booknumber is number but result is string.

Posted by hema on Saturday, 09.13.08 @ 15:38pm | #79113

Good Stuff very helpful!

Posted by Tree on Tuesday, 10.2.07 @ 11:33am | #30941

Latest Searches:
howtodeclareanarrayinj
getting dayname with d
extract
send file
Matrix Example in Java
read from files in jav
Treemap using gwt tree
how to scale image usi
Write a java program t
insert data in to mysq
how to store excel fil
jsp drop down menu
Reading File into Byte
jsp Insert insert data
commands
Easy UML Diagrams
Java Swing Center a Di
400 question
File InputStream
softwares
monthly calendar
text editor wiyh menu
Jfreechart Library
adding image in j2ee
Two-dimensional
disable minimize butto
visual jsf/
text box in swind
struts project
lookupDispatchAction i
ะà¸??ะà¸?ย ะà
JFreechart:Line3D
Unicast object
exampls
how to get the time di
how to configure msacc
JFreechart3D:Line3D
login form using mysql
Write a program to acc
binary to hexadecimal
switch case
get windows installati
??????Ñ?â??â??Ñ?â?????
get windows directory
display the sum of 20
JBOSS 5
Combattons la programm
JavaReadFileLinebyLine
java display applet me
ArrayList
Servlet Example To Dis
different Font
how to create a text f
J2ME UI components ort
Spring sample
java.io.*
jsp login by insertin
struts 1 date picker e
Aதà¯??தàÂ
insert fields blob
superscript in java
java applet repetitive
online
Combattons la programm
jQuery To Slide Effect
??????Ã¥??????????????
files read
count words character
align checkboxlist in
getQueryString
Call on extensible RMI
types of webserver
getQueryString()
java jtable
Why Virtual Dedicated
get url
upload file struts2
EXAMPLE PROGRAME USING
axis 2
rc4
Java String toLowerCase Example
Java String toCharArray Example
Java String substring Example
Java String indexOf Example
Java String startsWith Example
Java String hashCode Example
Java String matches Example
Java String length Example
Java String lastIndexOf Example
Java String isEmpty Example
Java String equalsIgnoreCase Example
Java String equals Example
Java String endsWith Example
Java String copyValueOf Example
Java String contentEquals Example
  EAI Articles
  Java Certification
Tell A Friend
Your Friend Name
Search Tutorials

 

 
 
Browse all Java Tutorials
Java JSP Struts Servlets Hibernate XML
Ajax JDBC EJB MySQL JavaScript JSF
Maven2 Tutorial JEE5 Tutorial Java Threading Tutorial Photoshop Tutorials Linux Technology
Technology Revolutions Eclipse Spring Tutorial Bioinformatics Tutorials Tools SQL
 

Home | JSP | EJB | JDBC | Java Servlets | WAP  | Free JSP Hosting  | Search Engine | News Archive | Jboss 3.0 tutorial | Free Linux CD's | Forum | Blogs

About Us | Advertising On RoseIndia.net  | Site Map

India News

Indian Software Development Company | iPhone Development Company in India | Java Training Delhi | Java Training at Noida |

Send your comments, Suggestions or Queries regarding this site at roseindia_net@yahoo.com.

Copyright © 2008. All rights reserved.