Browse DevX
Sign up for e-mail newsletters from DevX


Roll Your Own Swing-based XML Editor (Part II)-2 : Page 2




Building the Right Environment to Support AI, Machine Learning and Deep Learning

Enhance the XTree class
In the previous article, we developed the XTree class, a reusable component derived from the JTree class and capable of displaying XML data as a graphical tree. We will now enhance that class by providing it with a default XML tree to display in the event that an XML file is not supplied at the command-line. Additionally, we will also add some exception-handling logic so that the program will not crash due to invalid XML.

The first step is to create a method called buildTree():

private DefaultTreeModel buildTree( String text )
   DefaultMutableTreeNode  treeNode;
	Node				 newNode;

// Take the DOM root node and convert it to a Tree model
newNode = parseXml( text );

if ( newNode != null ) { treeNode = createTreeNode( newNode ); return new DefaultTreeModel( treeNode ); } else return null; } //end buildTree()

This method takes the XML text string passed to it, parses the XML and constructs a DefaultTreeModel that can then be used to construct the graphical tree structure from that data. This functionality had originally been contained in the XTree() constructor, but by taking it out and placing it in a separate method, we have the flexibility to create a default graphical tree. That is exactly what we will do next.

The next step is to create a method called buildWelcomeTree(). This method builds a DefaultTreeModel one piece at a time, rather than by parsing an existing string of XML text. This DefaultTreeModel will be displayed if the user starts the application without specifying an XML document.

Next we need to add a new constructor to facilitate this default display functionality. We will change the main constructor, so that it does not accept any arguments, and create a new constructor that accepts a single String of XML text. This way, the default XTree object will be created if no XML text will be displayed, and a unique XTree object will be created if the XML text is displayed. Both constructors can be seen in Listing 2.

Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date