Home > Java > javaTutorial > Create an XML editor using Java Swing (2)

Create an XML editor using Java Swing (2)

黄舟
Release: 2016-12-20 13:41:03
Original
2074 people have browsed it

This is the second article in this series. In the previous article, we briefly discussed xml and why a tree structure is suitable for displaying XML, how to process XML data, how to use the JTree Swing component and how to create a reusable XML document and display data in a Jtree components.
 

 In this article, we will create the framework of our XML editor. To achieve this purpose, we will use many Swing components (including jsplitPane, JscrollPane, Jbutton and JtextArea components).

 1. Problem Raising and Solving

  How can I create an XML text editor that can browse text and browse views? Create a Jframe object containing Jbutton and JsplitPane, and then let the JsplitPane object contain two JscrollPane objects, one for browsing graphics (xTree class) and the other for browsing text (JtextArea class). Jbutton is used to manage the operation of refreshing graphical browsing.

  2. Enhance the functions of the Xtree class

In the previous article, we developed the Xtree class, which is a reusable component that continues the Jtree class and can display XML data in the form of 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 . Furthermore, we will also add some error handling logic so that the program does 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 Become a Tree model

newNode = parseXml( text );
else

  return null;

 } file://end buildTree()

  This method gets the incoming XML string, analyzes the XML string and constructs a DefaultTreeModel variable instance that can be used to construct a graphical tree structure from the data . This functionality was originally included in the XTree() constructor, but we took it out and put it into a separate method so that we have the flexibility to create a default graphics tree. That's what we want to do next.

The next step is to create a method called buildWelcomeTree(). This method builds a DefaultTreeModel variable one at a time, rather than by parsing an existing XML literal string. If the user starts this application without specifying an XML file, the DefaultTreeModel will be displayed. See code snippet 1

Code snippet 1:

private DefaultTreeModel buildWelcomeTree()
{
 DefaultMutableTreeNode root;
 DefaultMutableTreeNode instrUCtions, openingDoc,
    EditingDoc, savingDoc;
 DefaultMutableTree Node 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
  in the right hand The "refresh" button will rebuild the JTree in the left frame." ); savingDoc = new DefaultMutableTreeNode

SavingDocText = new DefaultMutableTreeNode
       ( "This iteration of the XmlEditor does
    not provide the ability to save your
    document. add(editingDoc );
openingDoc.add( openingDocText );
editingDoc.add( editingDocText );
return new DefaultTreeModel( root );
}

Next we need to add a new constructor to simplify the default display functionality. We will modify the main constructor so that it cannot accept any parameters and create a new constructor that accepts a single XML text string. This way, a default XTree object is created if no XML text is displayed, and a unique XTree object is created if XML text is displayed. Two constructors are given in Code Fragment 2.

 Code snippet 2:

public setSelectionMode(
  TreeSelectionModel.SINGLE_TREE_SELECTION );
setShowsRootHandles( true );
setEditable( false );
dbf = DocumentBuilderFactory.newInstance();
dbf.setValidating( false );
db = dbf.newDocument Builder();
setModel( buildWelcomeTree () );
}

3. Create the XmlEditor class

 The XmlEditor class has the same purpose as the XTreeTester class in the previous article. The difference is that XmlEditor includes a JTextArea, which allows you to operate the text version of XML. Afterwards, you can click the "Refresh" button and see the changes reflected in the XTree component.

If you directly modify the code in the first article, you can save a lot of time. You can rename the XTreeTester.java file to XmlEditor.java (but you must modify the constructor) and use it as a template file.

The first thing to do is add the following Swing components: another JScrollPane, a JSplitPane, a JTextArea, and a JButton. Start by declaring all these components and others (see code snippet 3).

 Code snippet 3:

private This button is used to indicate that this XTree component will be refreshed with the current XML text. We also need to use an ActionListener to register it. (See code snippet 4) In order to intercept button events, we need to have this class and implement ActionListener, and we also need to create an actionPerformed() method (see code snippet 5).

 Code segment 4:

refreshButton = new JButton( "Refresh" );
refreshButton.setBorder(
 BorderFactory.createRaisedBevelBorder() );
refreshButton.addActionListener( this );
getContentPane().add( refreshButton, BorderLayout. NORTH );

Code segment 5:

public void actionPerformed( ActionEvent ae )
{
if ( ae.getActionCommand().equals( "Refresh" ) )


Next, we will create new JScrollPane and JTextArea and add JTextArea to JScrollPane. In this way, we will get the original JScrollPane containing the XTree component and the new JScrollPane containing the JTextArea component. There is one more modification to this original XTree constructor. We will remove the string parameter previously passed into this method. (This functionality is operated through another XmlEditor() constructor that we will build next.) We put these two boxes into a JSplitPane, which is a component with a divider that can be included on the other side of this divider a component. (See code snippet 6).

Code segment 6:

jScroll = new JScrollPane();
jScrollRt = new JScrollPane();

textArea = new JTextArea( 200,150 );
jScrollRt.getViewport().add( textArea );

xTree = new XTree();
xTree.getSelectionModel().setSelectionMode(
  TreeSelectionModel.SINGLE_TREE_SELECTION );
xTree.setShowsRootHandles( true );

xTree.setEditable( false );

splitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT,
  jScroll, jScrollRt );
splitPane.setOneTouchEXPandable(true);
splitPane.setDividerLocation(200);

minimumSize = new Dimension(200, 150);
jScroll.setMinimumSize( minimumSize );
jScrollRt.setMinimumSize( minimumSize );

splitPane.setPreferredSize( new Dimension(400, 300) );

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

Now we need to modify this constructor to Scenario that handles this non-XML file. Remove the second string parameter required by the current constructor. This constructor is now the default constructor. We will create a new constructor to receive a string parameter. It will first call the default constructor and then handle this parameter. (See Code Fragment 7) Furthermore, the main() method must be modified so that a default XmlEditor object can still be created in the event that there is no XML file. (See code snippet 8)

 Code snippet 7:

public XmlEditor( String title, ArrayList xmlText) throws
ParserConfigurationException
{
 this( title );
 textArea.setText( ( String )xmlText.get( 0 ) + " " );
 for ( int i = 1; i < xmlText.size(); i++ )
  textArea.append( ( String )xmlText.get( i ) + " " );
  xTree.refresh( textArea.getText() );
}

 代码段8:

public static void main( String[] args )
{
String fileName = "";
BufferedReader reader;
String line;
ArrayList xmlText = null;
XmlEditor xmlEditor;

try
{
if( args.length > 0 )
{
fileName = args[0];

if ( fileName.substring( fileName.indexOf( ´.´ ) ).equals( ".xml" ) )
{
reader = new BufferedReader( new FileReader( fileName ) );
xmlText = new ArrayList();

while ( ( line = reader.readLine() ) != null )
{
xmlText.add( line );
}

reader.close();

xmlEditor = new XmlEditor( "XmlEditor 1.0", xmlText );
}
else
{
help();
}

}
else
{
xmlEditor = new XmlEditor( "XmlEditor 1.0" );
}
}
catch( FileNotFoundException fnfEx )
{
System.out.println( fileName + " was not found." );
exit();
}
catch( Exception ex )
{
ex.printStackTrace();
exit();
}
}

  为了很轻易地处理 JTextArea数据,还需要最后一次必要的修改。一般我们不把这段文本当成一个长的字符串,而是把它当成一系列字符串,每行表示一个包含在数组列表中的字符串。这需要修改我们的构造程序接收的参数,并且修改在先前把这个数据作为一个字符串传入的那个main()方法中的任何调用。这还需要导入 java.util包 (参见代码段8 ) 。

  测试这个应用程序

  最后,我们必须添加一些异常处理到 XTree类中。假如你运行这个应用程序并输入无效的XML数据到 JTextArea中,这个程序就会崩溃。我们当然不想这样的事情发生。目前,我们把出错信息打印到命令行中。在下一篇文章中,我们将在一个图形对话框中显示出错信息。

  假如无效的或格式不好的 XML数据被输入 JTextArea然后按“Refresh”按钮,然后解析器将抛出一个错误,在本例中,parseXML()方法中包含的当前异常处理将立即退出。我们想要这个程序报告这个错误并返回一个空值来指出这个解析是不成功的。(见代码段9)你可能注重到 XTree类中的“buildTree()”和“refresh()”这两个方法有一个条件语句以避免处理空值。这是因为假如它们试着去处理一个空值它们也会报告异常。这个事件链保持程序流进行并且保持 XTree模型稳定。

  最后,我们就可以测试这个应用程序,测试过程我在这里就不多说了。 

 以上就是使用Java Swing 创建一个XML编辑器(二)的内容,更多相关内容请关注PHP中文网(m.sbmmt.com)! 


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template