Easy to Learn Java: Programming Articles, Examples and Tips

Start with Java in a few days with Java Lessons or Lectures

Home

Code Examples

Java Tools

More Java Tools!

Java Forum

All Java Tips

Books

Submit News
Search the site here...
Search...
 

Swing Chapter 17. (Advanced topics) Trees. Easy for reading, Click here!

Custom Search
Swing Chapter 17. (Advanced topics) Trees. Easy for reading, Click here!

[ Return to Swing (Book) ]

Page: 6/7 



Previous Page Previous Page (5/7) - Next Page (7/7) Next Page
Subpages: 1. JTree 
2.
Basic JTree example 
3.
Directories tree: part I - Dynamic node retrieval 
4. Directories tree: part II - Popup menus and programmatic navigation 
5. Directories tree: part III - Tooltips 
6. JTree and XML documents 
7. Custom editors and renderers 

17.6  JTree and XML documents

Many see the future of the web in XML (Extensible Markup Language). This standard will most likely replace HTML. Unlike HTML, XML allows the definition of custom document tags, allowing the transmition of virtually any type of information over the web. Many sources of information about XML are available, including the standard definition at http://www.w3.org/TR/WD-xml-lang-970331.html.

XML documents have a tree-like structure, and JTree can be very useful for constructing an XML structure browser. In this section we'll show how to build a simple implementation of such a browser. We do not intend to give an introduction to XML, and we will not discuss Sun's API for XML in detail (which contains a fair number of classes and is likely to change significantly in the near future). However, a brief introduction to the XML classes used in this example is appropriate.

Note: Sun's early access XML library is required to run this example. See http://www.javasoft.com/.

17.6.1  XmlDocument

class com.sun.xml.tree.XmlDocument

This class represents a top level XML 1.0 document created with the XML parser built into XmlDocumentBuilder. The getDocumentElement() method retrieves the top-most node in the document (i.e. the root node). All other nodes can be extracted through this node.

17.6.2  XmlDocumentBuilder

class com.sun.xml.tree.XmlDocumentBuilder

This class builds an XML document using an internal parser. Two overloaded methods, createXmlDocument(InputStream in) and createXmlDocument(String documentURL), create new XmlDocument instances. (We will use the latter method in this example.)

17.6.3  DataNode

class com.sun.xml.tree.DataNode

This class represents a node in an XML document tree that encapsulates data and has no child nodes (i.e. a leaf node). Method getData() retrieves the contained data as a String.

17.6.4  ElementNode

class com.sun.xml.tree.ElementNode

This class encapsulates an element in the XML document tree, which is a node with children (i.e. a non-leaf node). The getLength() method retrieves the number of child nodes, and item(int index) returns the node with the given index.

Figure 17.6 An XML document structure tree.

<<file figure17-6.gif>>

The Code: XmlTree.java

see \Chapter17\5

import java.awt.*;

import java.awt.event.*;

import java.util.*;

import java.io.*;

import java.net.*;

import javax.swing.*;

import javax.swing.tree.*;

import javax.swing.event.*;

import com.sun.xml.tree.*;

import com.sun.xml.parser.*;

import org.w3c.dom.*;

public class XmlTree extends JFrame

{

  protected JTree  m_tree;

  protected DefaultTreeModel m_model;

  protected JTextField m_location;

  public XmlTree() {

    super("XML Tree");

    setSize(400, 300);

    m_location = new JTextField();

    m_location.setText("samples\\book-order.xml");

    ActionListener lst = new ActionListener() {

      public void actionPerformed(ActionEvent e) {

        readXml(m_location.getText());

      }

    };

    m_location.addActionListener(lst);

    getContentPane().add(m_location, BorderLayout.NORTH);

    DefaultMutableTreeNode top = new DefaultMutableTreeNode(

      "Empty");

    m_model = new DefaultTreeModel(top);

    m_tree = new JTree(m_model);

    m_tree.getSelectionModel().setSelectionMode(

      TreeSelectionModel.SINGLE_TREE_SELECTION);

    m_tree.setShowsRootHandles(true);

      m_tree.setEditable(false);

    JScrollPane s = new JScrollPane();

    s.getViewport().add(m_tree);

    getContentPane().add(s, BorderLayout.CENTER);

    WindowListener wndCloser = new WindowAdapter() {

      public void windowClosing(WindowEvent e) {

        System.exit(0);

      }

    };

    addWindowListener(wndCloser);

    setVisible(true);

  }

  public void readXml(String sUrl) {

    setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));

    Thread runner = new Thread() {

      public void run () { 

        try {

          URL source;

          try {

            File f = new File(sUrl);

            source = f.toURL();

          }

          catch (Exception ex) {

            source = new URL(sUrl);

          }

          XmlDocument doc =

            XmlDocumentBuilder.createXmlDocument(

          source.toString());

          ElementNode root =

            (ElementNode)doc.getDocumentElement();

          root.normalize();

          DefaultMutableTreeNode top = createTreeNode(root);

          m_model.setRoot(top);

          m_tree.treeDidChange();

        }

        catch (Exception ex) {

          ex.printStackTrace();

          JOptionPane.showMessageDialog(this,

            ex.toString(), "Warning",

            JOptionPane.WARNING_MESSAGE);

        }

        setCursor(Cursor.getPredefinedCursor(

          Cursor.DEFAULT_CURSOR));

      }

    }

  }

  protected DefaultMutableTreeNode createTreeNode(ElementNode root) {

    DefaultMutableTreeNode node = new DefaultMutableTreeNode(

      root.getNodeName());

    for (int k=0; k<root.getLength(); k++) {

      Node nd = root.item(k);

      if (nd instanceof DataNode) {

        DataNode dn = (DataNode)nd;

        String data = dn.getData().trim();

        if (data.equals("\n") || data.equals("\r\n"))

          data = "";

        if (data.length() > 0)

          node.add(new DefaultMutableTreeNode(data));

      }

      else if (nd instanceof ElementNode) {

        ElementNode en = (ElementNode)nd;

        node.add(createTreeNode(en));

      }

    }

    return node;

  }

  public static void main(String argv[]) {

    new XmlTree();

  }

}

Understanding the Code

Class XmlTree

Instance variables:

JTree m_tree: used to display an XML document.

DefaultTreeModel m_model: used to store the content of an XML document.

JTextField m_location: used for entry of a file name or URL location of an XML document.

Initially the JTree component receives a single node, "Empty". An ActionListener is added to the m_location text field which calls our readXml() method passing it the current text.

The readXml() method loads an XML document, corresponding to the String passed as parameter, into our tree model. The body of this method is placed in a separate thread because it can be a very expensive procedure, and we want to make sure not to clog up the event dispatching thread (to retain GUI responsiveness). First the given string is treated as a file name. A File instance is created and converted to a URL. If this does not succeed, the string is treated as a URL address:

          URL source;

          try {

            File f = new File(sUrl);

            source = f.toURL();

          }

          catch (Exception ex) {

            source = new URL(sUrl);

          }

The static method XmlDocumentBuilder.createXmlDocument() creates an XmlDocument corresponding to the resulting URL. As soon as this finishes (which may take a while for large documents), the root ElementNode is retrieved from that document:

          XmlDocument doc =

            XmlDocumentBuilder.createXmlDocument(

          source.toString());

          ElementNode root =

            (ElementNode)doc.getDocumentElement();

          root.normalize();

We then transform our XML document into a structure suitable for addition to our Swing tree model. Our createTreeNode() method does this job, returning the top-most node (the root node) as a DefaultMutableTreeNode. Finally that node is set as a root of our tree model, and our tree component is notified that it's content has changed:

          DefaultMutableTreeNode top = createTreeNode(root);

          m_model.setRoot(top);

          m_tree.treeDidChange();

Note: Normally we are expected to avoid calling the treeDidChange() method directly, as it should be called by our UI as needed. However, in this case our JTree will not update correctly without it.

The createTreeNode() method creates a DefaultMutableTreeNode from an ElementNode provided. First it creates a root node corresponding to the given ElementNode, and then all lower level nodes are retrieved and processed in turn to populate the whole tree:

    DefaultMutableTreeNode node = new DefaultMutableTreeNode(

      root.getNodeName());

    for (int k=0; k<root.getLength(); k++) {

      Node nd = root.item(k);

Two possibilities are reconciled during this procedure. If a newly processed node is an instance of DataNode, its text is retrieved and is used as the user data object for a new DefaultMutableTreeNode which is then added to the parent node (in this case care should be taken to avoid empty nodes containing only end-of-line symbols). Otherwise, if a newly processed node is an instance of ElementNode, method createTreeNode() is called recursively.

Running the Code

Figure 17.6 shows our XML Tree example displaying the contents of "The Two Gentlemen of Verona" XML document which can be found at ftp://sunsite.unc.edu/pub/sun-info/standards/xml/eg/.



[ Return to Swing (Book) ]


Top 10 read Java Articles
 Get free "1000 Java Tips eBook"

 Java Calendar and Date: good to know facts and code examples

 Array vs ArrayList vs LinkedList vs Vector: an excellent overview and examples

 How can I convert any Java Object into byte array? And byte array to file object

 The Java Lesson 1: What is Java?

 How do I compare two dates and times, date between dates, time between times and

 Maven vs Ant or Ant vs Maven?

 How to open, read, write, close file(s) in Java? Examples on move, rename and de

 Java Array

 Java: JLabel font and color


[ More in News Section ]
Java Lessons

The Java Lesson 1:
What is Java?
The Java Lesson 2:
Anatomy of a simple Java program
The Java Lesson 3:
Identifiers and primitive data types
The Java Lesson 4:
Variables, constants, and literals
The Java Lesson 5:
Arithmetic operations, conversions, and casts
The Java Lesson 6:
Boolean expressions and operations
The Java Lesson 7:
Bitwise operations
The Java Lesson 8:
Flow control with if and else
The Java Lesson 9:
switch statements
The Java Lesson 10:
for, while, and do-while statements
The Java Lesson 11:
Using break and continue
The Java Lesson 12:
Class methods and how they are called
The Java Lesson 13:
Using the Math class
The Java Lesson 14:
Creating and calling custom class methods
The Java Lesson 15:
Overloading class methods
The Java Lesson 16:
An introduction to objects and object references
The Java Lesson 17:
The String class
The Java Lesson 18:
The StringBuffer class
The Java Lesson 19:
Initializing and processing arrays of primitives
The Java Lesson 20:
Initializing and processing arrays of objects
The Java Lesson 23:
Inheritance and overriding inherited methods
The Java Lesson 24:
abstract classes and polymorphism
The Java Lesson 25:
Interfaces, instanceof, and object conversion and casting
The Java Lesson 26:
Introduction to graphical programming and the java.awt packa
The Java Lesson 27:
The Component class
The Java Lesson 28:
Containers and simple layout managers
The Java Lesson 29:
The Color and Font classes
The Java Lesson 30:
Drawing geometric shapes
The Java Lesson 31:
Choice, List, and Checkbox controls
The Java Lesson 32:
Using the Scrollbar graphical control
The Java Lesson 33:
Menus and submenus
The Java Lesson 34:
An introduction to applets and the Applet class
The Java Lesson 35:
Essential HTML to launch an applet and pass it parameters
The Java Lesson 36:
Mouse event processing
Java Lesson 37:
Menus and submenus
Java Lesson 38:
The WindowListener interface and the WindowAdapter class
Java Lesson 39:
An introduction to GridBagLayout
Java Lesson 40:
An introduction to the Java Collections API
Java Lesson 41:
Exception handling with try, catch, and finally blocks
Java Lesson 42:
Claiming and throwing exceptions
Java Lesson 43:
Multithreading, the Thread class, and the Runnable interface
Java Lesson 44:
An introduction to I/O and the File and FileDialog classes
Java Lesson 45:
Low-level and high-level stream classes
Java Lesson 46:
Using the RandomAccessFile class
Java Lessons by
Joh Huhtala: Update

Latest articles
 Java Profiler JProbe to Resolve Performance Problems Faster

 SSL with GlassFish v2, page 5

 SSL with GlassFish v2, page 4

 SSL with GlassFish v2, page 3

 SSL with GlassFish v2, page 2

 The Java Lesson 2: Anatomy of a simple Java program, page 2

 New site about Java for robots and robotics: both software and hardware.

 Exceptions -III: What's an exception and why do I care?

 Exceptions -II: What's an exception and why do I care?

 Exceptions: What's an exception and why do I care?

 Double your Java code quality in 10 minutes, here is receipt

 Murach's Java Servlets and JSP

 How to get ascii code from a char in Java?

 Can we just try without catch? Yes!

 Make Tomcat page load faster

 Make your Tomcat More secure - limit network address for certain IP addresses

 New Java book online starts now here...

 Implementing RESTful Web Services in Java

 Firefox trimming from 1 GB to 40 Mb with many tabs opened

 SSL with GlassFish v2

 My request to replublish Tech Tips

 Search JavaFAQ.nu site here

 New Advanced Installer for Java 6.0 brings XML updates and imports 3rd party MSI

 EJB programming restrictions

 Maven vs Ant or Ant vs Maven?

 Why Java does not use default value which it should?

 How to unsign signed bytes in Java - your guide is here

 The Java Lesson 3: Identifiers and primitive data types. Page 2

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 4

 The Java Lesson 7: Bitwise operations with good examples, click here! Page 3


[ More in News Section ]


Home Code Examples Java Forum All Java Tips Books Submit News, Code... Search... Offshore Software Tech Doodling

RSS feed Java FAQ RSS feed Java FAQ News     

    RSS feed Java Forums RSS feed Java Forums

All logos and trademarks in this site are property of their respective owner. The comments are property of their posters, all the rest 1999-2006 by Java FAQs Daily Tips.

Interactive software released under GNU GPL, Code Credits, Privacy Policy