Welcome 微信登录

首页 / 软件开发 / JAVA / 使用Java Swing创建一个XML编辑器之二

使用Java Swing创建一个XML编辑器之二2010-12-16这是本系列的第二篇文章。在上一篇文章中,我们简要地讨论了XML以及为什么一个树形结构适合显示XML、如何处理XML数据、如何使用JTree Swing 组件以及如何创建一个可重用的能够分析XML文档以及在Jtree显示数据的组件。

在本文中,我们将创建我们的XML编辑器的框架,为了达到这个目的,我们将用到许多Swing组件(包括JsplitPane、JscrollPane、Jbutton和JtextArea组件)。

一、问题的提出与解决

我如何创建一个能够浏览文本和浏览视图的XML文本编辑器呢?创建一个包含Jbutton和JsplitPane的Jframe对象, 然后让JsplitPane对象包含两个JscrollPane对象,一个用于浏览图形(xTree类),另一个用于浏览文本(JtextArea类)。Jbutton用来管理刷新图形浏览的操作。

二、增强Xtree类的功能

在上一篇文章中,我们开发了Xtree类,这是一个可重用的组件,继承于Jtree类并能够把XML数据以图形树的形式显示。我们现在就增强这个类, 通过提供给它一个在显示默认的XML树来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. 而且,我们还将添加一些错误处理逻辑以便程序不会因为无效的XML而崩溃。

第一步是创建一个名为buildTree()的方法:

private DefaultTreeModel buildTree( String text )
{
DefaultMutableTreeNode treeNode;
Node newNode;
// 采用DOM根节点并把它转化成为一个Tree模型
newNode = parseXml( text );
if ( newNode != null )
{
treeNode = createTreeNode( newNode );
return new DefaultTreeModel( treeNode );
}
else
return null;
} file://结束buildTree()

这个方法取得传入的 XML字符串,分析这个 XML字符串并构造一个可以用来从数据中构造图形树形结构的DefaultTreeModel变量实例。这个功能原来包含在 XTree()构造程序中,但是我们把它拿出来然后把它放进一个单独的方法中,这样我们就有了创建一个默认图形树的伸缩性。这就是我们接下来想做的事。

接下来一步是创建一个叫 buildWelcomeTree()的方法。这个方法一次构建一个DefaultTreeModel变量,而不是通过分析一个现有的XML文字字符串。如果用户没有指定 XML文件就启动这个应用程序,将显示 DefaultTreeModel。见代码段1

代码段1:

private DefaultTreeModel buildWelcomeTree()
{
DefaultMutableTreeNode root;
DefaultMutableTreeNode instructions, openingDoc,
editingDoc, savingDoc;
DefaultMutableTreeNode openingDocText, editingDocText,
savingDocText;
DefaultMutableTreeNode development, addingFeatures,
contactingKyle;
root = new DefaultMutableTreeNode( "Welcome to XML View 1.0" );
instructions = new DefaultMutableTreeNode( "Instructions" );
openingDoc = new DefaultMutableTreeNode
( "Opening XML Documents" );
openingDocText = new DefaultMutableTreeNode
( "When invoking the XmlEditor from
the command-line, you must specify the filename." );
editingDoc = new DefaultMutableTreeNode
( "Editing an XML Document" );
editingDocText = new DefaultMutableTreeNode
( "XML text in the right hand frame
can be edited directly.
The "refresh" button will rebuild
the JTree in the left frame." );
savingDoc = new DefaultMutableTreeNode
( "Saving an XML Document" );
savingDocText = new DefaultMutableTreeNode
( "This iteration of the XmlEditor does
not provide the ability to save your
document. That will come with the
next article." );
root.add( instructions );
instructions.add( openingDoc );
instructions.add( editingDoc );
openingDoc.add( openingDocText );
editingDoc.add( editingDocText );
return new DefaultTreeModel( root );
}