Creating an XML editor with Java Swing

Source: Internet
Author: User
Tags end final header object model variables simple xml editor string variable
xml| Create

I'm sure you have some knowledge of XML, and you might be tempted to write an XML text now, but there are so few cross-platform, free XML editors you can find now. So in this article, I would like to introduce or take you step-by-step to develop a simple XML editor, of course we want to use some of the most common Java 2 swing components, but these are free, some are JDK, some can be downloaded from the Internet. I think through this article, you can create an XML editor that belongs to you.

First, let me introduce the idea of writing. First I want to briefly discuss XML and why the tree structure is more suitable for displaying XML, and then let's take a look at how the JAXP API creates the XML class that it needs, and then we'll learn about the JTree swing component that displays a graph tree; We will create a reusable class that inherits the JTree component, which can be used to parse an XML document and display the data in a jtree.

When it comes to XML (extensible Markup Languge), people tend to think of it as a new markup language for Web browsers, just like HTML or CSS. In fact, XML is a data representation language that allows you to use a very efficient way to describe your data. XML enables you to define statements such as "these three words constitutes a heading". XML allows you to declare any type of data instead of displaying it in a Web page.

Take a look at the following XML instance:



use Java Swing to create an XML editor<br><subtitle> First Part </subtitle><br>
Wayne

This is the body


Note that these elements are different from standard HTML statements, but they look more like HTML because both XML and HTML originate from the SGML language. The difference is that HTML has a predefined set of tags, and the syntax of XML has a lot of flexibility, which allows you to use ideographic markup such as to enclose the data on both sides. You should also note that all elements are subordinate to the root element (

in the example above), and some elements have their own child elements, such as is the child element of . This data organization has three benefits: data is more expressive, data is easier to maintain, and data is more easily represented as a tree, which is why we use the JTree object to display XML data. If you want to have a deeper understanding of XML, see the tutorials on Tenkine.</p>

JAXP is a Java API for working with XML that enables applications to parse and transform XML documents, a bit like the JDBC API, which abstracts function functions into a single method. You can go to the Apache website to find the latest Xerces Analyzer, which contains the latest JAXP, download it and put it in your class directory.

Now let's look at how to use the JTree swing component.

As we all know, in nature, a tree usually has a very thick trunk, there are many branches on the trunk branch fork. There is a certain connection between each branch and the branch, because they all have the same source: the trunk. This inherited relationship is not only in the branches, but the human lineage follows the same pattern. From the parents, to the children and the children, so until countless. Similarly, in data storage, the concept of a tree is also a way to store data in the same way as a human family tree. Each branch of the tree is called a node, each node that has a child node is called the parent node, and the common parent of all child nodes is called the root node. A JTree component is a visual representation of a simple tree data structure.

Almost all XML editors include a visual tree structure that allows you to edit the elements in an XML document. We'll build an editor right away, but before we do, let's take a look at the JTree component. A node stores data somewhere in a tree, and in order to store data, you must know any parent node and their child nodes. The Javax.swing.tree package defines some very useful interfaces, providing a common way to build and manipulate a tree structure.

TreeNode method, which is used to access the information of the node of the tree

The Mutabletreenode method is used on a variable tree (ability to add or remove child nodes)

The TreeModel method is used to create and manage tree-related data models.

Next, we will create a class that inherits JTree, providing the ability to parse XML documents and display nodes with visual JTree components.

Creating XTree Components

The XTree class consists of a constructor and three methods, for the sake of simplicity our component can only build a xtree that cannot be processed after the tree is created. Let's take a look at one of the classes below.

Domain:

Private Defaultmutabletreenode TreeNode This member variable stores the Model TreeNode object is used to store jtree.

The Defaultmutabletreenode class is defined in Javax.swing.tree and provides an implementation of the Mutabletreenode interface by default.

Private Documentbuilderfactory DBF

Private Documentbuilder DB

Private Document Doc These three member variables are part of JAXP, which is used to parse the XML text and transform it into a DOM (Document object Model) object.

Constructors

Public XTree (String text)

This constructor creates a XTree object by using the XML text that is passed to the constructor. After initializing some of the basic display properties associated with the JTree superclass and Dom parsing objects, the constructor generates a TreeModel object to create an actual visual tree. By passing the DOM object to the Createtreenode () method to create a root node, the Createtreenode () method returns an object of the Defaultmutabletreenode type. This object is then used to create the treemodel of the tree.

Method

Private Defaultmutabletreenode Createtreenode (Node root)

This method takes a DOM node and then recursively in the child nodes until all the contacts are added to the Defaultmutabletreenode. This is a recursive method that, in order to find each child node under the root node, calls itself each time. JTree then you can use the Defaultmutabletreenode object, because it's already a tree type.

Private String Getnodetype (node node)

Now let's look at how to use the JTree swing component.

As we all know, in nature, a tree usually has a very thick trunk, there are many branches on the trunk branch fork. There is a certain connection between each branch and the branch, because they all have the same source: the trunk. This inherited relationship is not only in the branches, but the human lineage follows the same pattern. From the parents, to the children and the children, so until countless. Similarly, in data storage, the concept of a tree is also a way to store data in the same way as a human family tree. Each branch of the tree is called a node, each node that has a child node is called the parent node, and the common parent of all child nodes is called the root node. A JTree component is a visual representation of a simple tree data structure.

Almost all XML editors include a visual tree structure that allows you to edit the elements in an XML document. We'll build an editor right away, but before we do, let's take a look at the JTree component. A node stores data somewhere in a tree, and in order to store data, you must know any parent node and their child nodes. The Javax.swing.tree package defines some very useful interfaces, providing a common way to build and manipulate a tree structure.

TreeNode method, which is used to access the information of the node of the tree

The Mutabletreenode method is used on a variable tree (ability to add or remove child nodes)

The TreeModel method is used to create and manage tree-related data models.

Next, we will create a class that inherits JTree, providing the ability to parse XML documents and display nodes with visual JTree components.

Creating XTree Components

The XTree class consists of a constructor and three methods, for the sake of simplicity our component can only build a xtree that cannot be processed after the tree is created. Let's take a look at one of the classes below.

Domain:

Private Defaultmutabletreenode TreeNode This member variable stores the Model TreeNode object is used to store jtree.

The Defaultmutabletreenode class is defined in Javax.swing.tree and provides an implementation of the Mutabletreenode interface by default.

Private Documentbuilderfactory DBF

Private Documentbuilder DB

Private Document Doc These three member variables are part of JAXP, which is used to parse the XML text and transform it into a DOM (Document object Model) object.

Constructors

Public XTree (String text)

This constructor creates a XTree object by using the XML text that is passed to the constructor. After initializing some of the basic display properties associated with the JTree superclass and Dom parsing objects, the constructor generates a TreeModel object to create an actual visual tree. By passing the DOM object to the Createtreenode () method to create a root node, the Createtreenode () method returns an object of the Defaultmutabletreenode type. This object is then used to create the treemodel of the tree.

Method

Private Defaultmutabletreenode Createtreenode (Node root)

This method takes a DOM node and then recursively in the child nodes until all the contacts are added to the Defaultmutabletreenode. This is a recursive method that, in order to find each child node under the root node, calls itself each time. JTree then you can use the Defaultmutabletreenode object, because it's already a tree type.

Private String Getnodetype (node node)

This method, which is Createtreenode (), is used to contact a string and a node of a certain type.

Private Node Parsexml ()

This method, which is used to parse an XML text string, returns the node type object that can be routed to the Createtreenode () method.
Below I give the Java code, for you to analyze and study.

To the DOM class into the consortium
Import org.w3c.dom.*;
JAXP's class for Dom I/O
Import javax.xml.parsers.*;
Standard Java class
Import javax.swing.*;
Import javax.swing.tree.*;
Import javax.swing.event.*;
Import java.awt.*;
Import java.awt.event.*;
Import java.io.*;
public class XTree extends JTree
{
/**
* This member variable stores the TreeNode object used to store the JTree model.
The *defaultmutabletreenode class is defined in Javax.swing.tree
* An implementation of the Mutabletreenode interface is provided by default.
*/
Private Defaultmutabletreenode TreeNode;
/**
* These three member variables are part of JAXP, which is used to parse the XML text and transform it into a DOM (Document object Model) object.
*/
Private Documentbuilderfactory DBF;
Private Documentbuilder DB;
Private Document Doc;

/**
* This constructor creates a XTree object by using the XML text that is passed to the constructor

* @ parameter text is an XML-formatted XML literal

* @ Exception Parserconfigurationexception throws an exception if the constructor does not have a normal setup parser

*/

Public XTree (String text) throws Parserconfigurationexception
{
Super ();

Set basic properties for tree rendering
Getselectionmodel (). Setselectionmode (treeselectionmodel.single_tree_selection);
Setshowsroothandles (TRUE);
Seteditable (FALSE); Allow trees to edit

To parse an object by initializing the DOM of the object
DBF = Documentbuilderfactory.newinstance ();
Dbf.setvalidating (FALSE);
db = Dbf.newdocumentbuilder ();

Using the DOM root node and converting it into a jtree tree model
TreeNode = Createtreenode (parsexml (text));
Setmodel (New Defaulttreemodel (TreeNode));
} file://abort XTree ()

/**

* This method takes a DOM node and then recursively in the child nodes until all the contacts are added to the Defaultmutabletreenode.

* This is a recursive method, in order to find each child node under the root node, it calls itself each time.

* JTree then you can use the Defaultmutabletreenode object, because it's already a tree type.

*

* @ parameter root Org.w3c.Node.Node

*

* The @ return value returns a Defaultmutabletreenode object based on the root node

*/


Private Defaultmutabletreenode Createtreenode (Node root)
{
Defaultmutabletreenode treeNode = null;
String type, name, value;
NamedNodeMap attribs;
Node Attribnode;

Getting data from the root node
Type = Getnodetype (root);
Name = Root.getnodename ();
Value = Root.getnodevalue ();

TreeNode = new Defaultmutabletreenode (root.getnodetype () = = Node.text_node? value:name);

Display Properties
Attribs = Root.getattributes ();
if (attribs!= null)
{
for (int i = 0; I attribs.getlength (); i++)
{
Attribnode = Attribs.item (i);
Name = Attribnode.getnodename (). Trim ();
Value = Attribnode.getnodevalue (). Trim ();

if (value!= null)
{
if (Value.length () 0)
{
Treenode.add (New Defaultmutabletreenode ("[Attribute]-->" + name + "=\" "+ Value +" \ "));
} file://end if (Value.length () > 0)
} file://end if (value!= null)
File://end for (int i = 0; I attribs.getlength (); i++)
} file://end if (attribs!= null)

If a child node exists, recursion
if (Root.haschildnodes ())
{
NodeList children;
int Numchildren;
Node node;
String data;

Children = Root.getchildnodes ();
Recursive only if the child node is not empty
if (children!= null)
{
Numchildren = Children.getlength ();

for (int i=0; I numchildren; i++)
{
node = Children.item (i);
if (node!= null)
{
if (node.getnodetype () = = Node.element_node)
{
Treenode.add (Createtreenode (node));
} file://end if (node.getnodetype () = = Node.element_node)

data = Node.getnodevalue ();

if (data!= null)
{
data = Data.trim ();
if (!data.equals ("\ n") &&!data.equals ("\ r \ n") && Data.length () > 0)
{
Treenode.add (Createtreenode (node));
File://end if (!data.equals ("\ n") &&!data.equals ("\ r \ n") && Data.length () > 0)
} file://end if (data!= null)
} file://end if (node!= null)
File://end for (int i=0; I numchildren; i++)
} file://end if (children!= null)
} file://end if (Root.haschildnodes ())
return treeNode;
} file://end Createtreenode (Node root)

/**

* This method, which is Createtreenode (), is used to contact a string and a node of a certain type.

*

* @ parameter Node Org.w3c.Node.Node

*

* @ return value returns the string showing the node class

*/

Private String Getnodetype (node node)
{
String type;

Switch (Node.getnodetype ())
{
Case Node.element_node:
{
Type = "Element";
Break
}
Case Node.attribute_node:
{
Type = "Attribute";
Break
}
Case Node.text_node:
{
Type = "Text";
Break
}
Case Node.cdata_section_node:
{
Type = "CData section";
Break
}
Case Node.entity_reference_node:
{
Type = "Entity reference";
Break
}
Case Node.entity_node:
{
Type = "Entity";
Break
}
Case Node.processing_instruction_node:
{
Type = "processing instruction";
Break
}
Case Node.comment_node:
{
Type = "Comment";
Break
}
Case Node.document_node:
{
Type = "Document";
Break
}
Case Node.document_type_node:
{
Type = "Document type";
Break
}
Case Node.document_fragment_node:
{
Type = "Document fragment";
Break
}
Case Node.notation_node:
{
Type = "notation";
Break
}
Default
{
Type = "???";
Break
}
}//End Switch (Node.getnodetype ())
return type;
} file://end Getnodetype ()

/**

* This method, which is used to parse an XML text string, returns the node type object that can be transferred to the Createtreenode () method.

*

* @ parameter text A string that displays an XML document

* @ return value returns a Org.w3c.Node.Node object

*/


Private Node Parsexml (String text)
{
Bytearrayinputstream ByteStream;

ByteStream = new Bytearrayinputstream (Text.getbytes ());

Try
{
doc = Db.parse (ByteStream);
}
catch (Exception e)
{
E.printstacktrace ();
System.exit (0);
}
Return (Node) doc.getdocumentelement ();
} file://end Parsexml ()

} file://End Class XTree


Code 2 Xtreetester.java

Import javax.xml.parsers.*;

GUI class
Import javax.swing.*;
Import java.awt.*;
Import java.awt.event.*;

FILE://standard Java class
Import java.io.*;


public class Xtreetester extends JFrame
{
XTree object that is used to display XML in JTree
Private XTree XTree;
JScrollPane is a jtree container.
Private JScrollPane Jscroll;
Private WindowListener winclosing;

Set the width and height of the frame
private static final int frame_width = 400;
private static final int frame_height = 300;

/*

* constructor constructs a framework that contains JScrollPane,

* Upload a XTree object based on an XML string into the constructor

*/

Public Xtreetester (string title, String xml) throws Parserconfigurationexception
{
Super (title);

Toolkit Toolkit;
Dimension Dim, MinimumSize;
int screenheight, screenwidth;

Initialize Basic layout Properties
SetBackground (Color.lightgray);
Getcontentpane (). setlayout (New BorderLayout ());
Toolkit = Toolkit.getdefaulttoolkit ();
Dim = Toolkit.getscreensize ();
ScreenHeight = Dim.height;
ScreenWidth = Dim.width;
SetBounds ((screenwidth-frame_width)/2, (Screenheight-frame_height)/2, frame_width, frame_height);

Building XTree Objects
XTree = new XTree (XML);

file://encapsulates xtree into Jscroll so that it can scroll up and down the screen in JFrame.
Jscroll = new JScrollPane ();
Jscroll.getviewport (). Add (XTree);

Add scroll bar to frame
Getcontentpane (). Add (Jscroll, borderlayout.center);
Validate ();
SetVisible (TRUE);
Add WindowListener to close a window
winclosing = new Windowadapter ()
{
public void windowclosing (WindowEvent e)
{
Exit ();
}
};
Addwindowlistener (winclosing);
}

The program starts here. An XML file with an XML extension must be routed to this method, in the form of a Java xtreetester yourxmlfilename.xml

public static void Main (string[] args)
{
String fileName = "";
BufferedReader reader;
String Line;
StringBuffer XmlText;
Xtreetester Xtreetester;

Create a Document object based on a specific XML file
Try
{
if (Args.length > 0)
{
FileName = Args[0];

if (filename.substring filename.indexof ('. ')). Equals (". xml"))
{
reader = new BufferedReader (fileName) (new FileReader);
XmlText = new StringBuffer ();

while (line = Reader.readline ())!= null)
{
Xmltext.append (line);
}

Files are overwritten after the document object is parsed
Reader.close ();

Constructing GUI Components
Xtreetester = new Xtreetester ("XTree test", xmltext.tostring ());
}
Else
{
Help ();
}
}
Else
{
Help ();
}
}
catch (FileNotFoundException Fnfex)
{
System.out.println ("no + fileName +" file was found.) " );
Exit ();
}
catch (Exception ex)
{
Ex.printstacktrace ();
Exit ();
}
}

file://Help Information

private static void Help ()
{
System.out.println ("\ n Use method: Java xtreetester yourxmlfilename.xml");
System.exit (0);
}

Exit
private static void Exit ()
{
SYSTEM.OUT.PRINTLN ("Thank you for using XTree");
System.exit (0);
}

}



Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.