在本文中,我们将创建我们的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 document.\" ); 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 ); } 接下来的我们需要添加一个新的构造程序来简化默认显示功能,我们将修改主构造程序,这样它就不能接受任何参数,创建一个新的能接收单一的 XML文本字符串的构造程序。这样以来,如果没有 XML文本被显示的话就会创建默认 XTree对象,而如果 XML文本被显示的话将创建一个唯一的 XTree对象。代码段2中给出了两个构造程序。 代码段2: public XTree( String text ) throws ParserConfigurationException { this(); ref[1] [2] 下一页
|
|