WebNFS Developer's Guide

The DemoEditor Sample Program

The DemoEditor program allows a user to open a text file and perform simple edits on it (Cut, Paste, etc.). The file can then be saved to another name.

Figure 5-6 The DemoEditor Program

Graphic

As part of the initialization of the application,

  1. menu items are created for opening, closing, and saving a file, and for exiting;

  2. listeners are added to the menu items;

  3. the menu items are attached to the File menu.

For brevity's sake, only the code for opening files is shown below:


JMenu filemenu = new JMenu("File");
openItem = new JMenuItem("Open");
openItem.addActionListener(this);
fileMenu.add(openItem);

If an item on the File menu is selected, an actionEvent is fired off which causes the actionPerformed() method to be called. actionPerformed() checks the type of menu item selected and acts accordingly: it creates an XFileChooser object, and, if Open or Save is selected from the menu, brings up a file chooser.


public void actionPerformed(ActionEvent ae) {
   int retval;
   XFileChooser chooser = new XFileChooser();
   if (ae.getSource == closeItem)
     closeDocument();
   } else if (ae.getSource() == openItem) {
      retval = chooser.showOpenDialog(this);
      if (retval == XFileChooser.APPROVE_OPTION) {
        XFile theFile = chooser.getSelectedXFile();
   // make sure we're not already editing a file!
        closeDocument(); 
        if (theFile != null)
          readFromFile(theFile);
     }
   } else if (ae.getSource() == saveItem) {
     retval = chooser.showSaveDialog(this);
     if (retval == XFileChooser.APPROVE_OPTION) {
        XFile theFile = chooser.getSelectedXFile();
        if (theFile != null)
          writeToFile(theFile);
        }
   } else if (ae.getSource() == exitItem) {
     System.exit(0);
   }
}

Some things to note about the foregoing: