Home >Java >javaTutorial >Create an XML editor using Java Swing (3)
If you are looking for a cross-platform, open-resource XML editor, you may soon be able to realize this wish. In this three-part series, I'll walk you through developing a simple XML editor using some of the most common Java 2 Swing components. This series will benefit those who want to write their own XML editor or help you learn or brush up on Swing.
This is the third article in this series. In the first article, we briefly discussed XML and why tree structures are suitable for displaying XML, how to process XML data, how to use the JTree Swing component, and we also built a reusable component to parse XML files and use them in JTree Display data in .
In the second article, we created the skeleton structure for our XML editor. To do this, we talked about a number of Swing components (including jsplitPane, JScrollPane, JButton, and JTextArea). The JSplitPane object contains two JScrollPane objects, one for graphical browsing of XML and the other for text browsing.
In this last article, we will add the final interface to the XML editor to make it more user-friendly. We will first build a menu system, and then continue to construct the JFileChooser component that accesses the underlying file system to allow saving XML files and opening new documents. Finally, we will build a JDialog box that enables the user to cancel a command and exit the application.
So how do we enhance the performance of our Swing applications so that they utilize menus, access the file system and allow the user to cancel operations? We need to create a JMenu component to handle the application's menu, a JFileChooser component to access the underlying file system, and a JDialog box to allow the user to cancel the operation.
In previous articles, we developed the XTree class, a reusable component derived from the JTree class that can display XML data as a graphical tree. Because we like to use object-oriented principles, the changes we make today won't touch that class. Because we like to use object-oriented principles, the changes we make today won't touch that class. It is a self-contained reusable class that is used by our JFrame container rather than being combined.
Section 1 Building a Menu Component
A JMenu component includes several objects: a menu bar, one or more menus, and one or more menu items. Menu bars contain menus, which contain menu items. The names of these Swing components are quite intuitive (JMenuBar, JMenu, and JMenuItem respectively).
Here is the entire code to create a minimal "File" menu containing a single menu item:
JMenu fileMenu = new JMenu( "File" );
JmenuItem exitItem = new JMenuItem( "Exit" );
fileMenu .add( exitItem );
JmenuBar menuBar = new JMenuBar();
menuBar.add( fileMenu );
setJMenuBar( menuBar );
This process should be very familiar to us, the JMenu component is used in any other Java GUI component Created at build time. Innermost elements are added to their immediate parent elements until all elements have an appropriate container defined.
Returning to the XmlEditor case study, we have actually created a complete file menu with the ability to create a new XML file, open an existing file, save the file, and exit. We'll talk more about it in the next section.
Section 2 Handling Menu Events
We want to create a typical file menu that allows our users to create a new document, open an existing file, save the current file and exit the application. Now that we know how to build this menu, how do we respond to the user's menu selections? As with other Swing components, the answer lies in the event model and the available listener components.
The most basic way to handle a menu selection is to add an action listener to the menu item: exitItem.addActionListener(new exitMenuHandler()); when dealing with complex event handling (because the menu system may become very complex) , event handlers should be defined as separate classes. The example given above adds an action listener of type exitMenuHandler. This type will be defined later in this application. Here is the minimal code required to define the exitMenuHandler class:
class exitMenuHandler implements ActionListener {
public void actionPerformed( ActionEvent ae ) {
System.exit(0);
}
}
Although this implementation is used to verify a single The class definition may seem too simple, but when we define the event handling code for opening and saving files, you will become familiar with the importance of putting separate functionality into separate class files. Additionally, this approach will allow you to reuse common menu functionality across different applications.
Section 3: Building file system access components
This Java application often needs to allow users to access the file system through a graphical file system browser. Typically, this is because the user wants to open or save a component or file. In our XmlEditor application, we want the user to be able to do this.
To access the basic file system, there is a very good component in the javax.swing package: the JFileChooser component. Undoubtedly, you have already used a Swing application before taking advantage of the JFileChooser component.
To create a JFileChooser, you first instantiate a JFileChooser object, set its size and then declare it to be used to either open files or save files. You link this object to its parent - the object used to activate it (in our case a menu item) - and then set it to either open the dialog or save the dialog. To do this, you use the showSaveDialog() or showOpenDialog() methods, both of which return an int return value. Here is a short example:
JFileChooser jfc = new JFileChooser();
jfc.setSize( 500, 250 );
Container parent = openItem.getParent();
int choice = jfc.showOpenDialog(parent);
The last line returns an integer value indicating whether the user finally opened/saved a file or pressed the cancel button. In response to open/save events, this integer value can be compared with the APPROVE_OPTION constant defined in the JFileChooser class. At this point, you just need to use the appropriate method to open/save the file requested by the user.
Please refer to code snippet 1, which is the complete implementation of this application; it contains all six methods used to construct the menu processing function of the XmlEditor application.
Section 4 Build a dialog component to validate selections
Now, when you click the Jframe's close window, the application closes immediately. This is not good. What if the user accidentally closes the window while working on a file? We want to prompt the user and ask them if they really want to close the application.
We can use a JDialog dialog box to achieve this purpose. Every graphics application can use them to alert the user before they overwrite another file, close a file without saving, or before closing the application. In order to simplify programming, we focus on reminding the user when closing the editor.
What we need to do is create a JDialog dialog box. This dialog box is equipped with a Jlabel. It contains a prompt and two buttons, one to receive the command to close the program, and the other to cancel the command to close the program. The following is the code to construct this component:
JDialog verifyDialog = new JDialog( this, "Confirm Exit", true );
Jlabel question = new JLabel( "Are you sure you want to exit?" );
Jbutton okButton = new JButton( "OK" );
okButton.addActionListener( this );
Jbutton cancelButton = new JButton( "Cancel" );
cancelButton.addActionListener( this );
verifyDialog.getContentPane().setLayout( new FlowLayout() );
verifyDialog.getContentPane().add( question );
verifyDialog.getContentPane().add( okButton );
verifyDialog.getContentPane().add( cancelButton );
verifyDialog.hide();
Now, there are two left Nothing was done. We must write event handling code for these two buttons and replace the window close event behavior with them. As far as handling these two buttons is concerned, we simply close the application when OK is pressed and hide the dialog when Cancel is pressed.
The last step is to override the default window close event action. By default, even if you create a dialog box and the user clicks the cancel button, JFrame still receives the close window event. This will cause the JFrame to hide itself unless we override it with the following setting:
setDefaultCloSEOperation( JFrame.DO_NOTHING_ON_CLOSE );
The new setting will never close itself in response to the window closing event. It only closes itself in response to a System.exit() call.
Once you have added the menu component, defined event handlers for the menu events and added a method to cancel the unexpected window closing event, we can test the application and start creating, editing and saving XML files.
Congratulations! Congratulations! You already have a hand-written Swing-based XML editor. The rest of the work is up to you, you need to verify it, increase its robustness, and maybe add some new features.
Attachment: Code snippet 1
class newMenuHandler implements ActionListener
{
public void actionPerformed ( ActionEvent ae )
{
textArea.setText( "" );
try
{ // Create a new XTree
xTree = new XTree ();
;
}
catch( Exception ex )
{
String message = ex.getMessage();
ex.printStackTrace();
}
file://结束try/catch
}
file://结束actionPerformed()
}
file://结束class newMenuHandler
class openMenuHandler implements ActionListener
{
JFileChooser jfc;
Container parent;
int choice;
openMenuHandler()
{
super();
jfc = new JFileChooser();
jfc.setSize( 400,300 );
jfc.setFileFilter( new XmlFileFilter() );
parent = openItem.getParent(); }
file://结束openMenuHandler()
class openMenuHandler implements ActionListener
{
JFileChooser jfc;
Container parent;
int choice;
openMenuHandler()
{
super();
jfc = new JFileChooser();
jfc.setSize( 400,300 );
jfc.setFileFilter( new XmlFileFilter() );
parent = openItem.getParent();
}
public void actionPerformed( ActionEvent ae )
{
choice = jfc.showOpenDialog( parent );
if ( choice == JFileChooser.APPROVE_OPTION )
{
String fileName, line;
BufferedReader reader;
fileName = jfc.getSelectedFile().getAbsolutePath();
try
{
reader = new BufferedReader(
new FileReader( fileName ) );
textArea.setText( reader.readLine() + " " );
while ( ( line = reader.readLine() ) != null )
{
textArea.append( line + " " );
}
reader.close();
xTree.refresh( textArea.getText() );
}
catch ( Exception ex )
{
String message = ex.getMessage();
ex.printStackTrace();
}
jfc.setCurrentDirectory( new File( fileName ) );
}
}
}
class saveMenuHandler implements ActionListener
{
JFileChooser jfc;
Container parent;
int choice;
saveMenuHandler()
{
super();
jfc = new JFileChooser();
jfc.setSize( 400,300 );
jfc.setFileFilter( new XmlFileFilter() );
parent = saveItem.getParent();
}
public void actionPerformed( ActionEvent ae )
{
choice = jfc.showSaveDialog( parent );
if ( choice == JFileChooser.APPROVE_OPTION )
{
String fileName;
File fObj;
FileWriter writer;
fileName = jfc.getSelectedFile().getAbsolutePath();
try
{
writer = new FileWriter( fileName );
textArea.write( writer );
writer.close();
}
catch ( IOException ioe )
{
ioe.printStackTrace();
}
jfc.setCurrentDirectory( new File( fileName ) );
}
}
}
class exitMenuHandler implements ActionListener
{
public void actionPerformed( ActionEvent ae )
{
verifyDialog.show();
}
}
class XmlFileFilter extends javax.swing.filechooser.FileFilter
{
public boolean accept( File fobj )
{
if ( fobj.isDirectory() )
return true;
else
return fobj.getName().endsWith( ".xml" );
}
public String getDescription()
{
return "*.xml";
}
}
以上就是使用Java Swing 创建一个XML编辑器(三)的内容,更多相关内容请关注PHP中文网(www.php.cn)!