DemoEditor
Sample ProgramThe 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.
DemoEditor
ProgramAs part of the initialization of the application,
menu items are created for opening, closing, and saving a file, and for exiting;
listeners are added to the menu items;
the menu items are attached to the File menu.
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:
All the file I/O involves XFile objects, not File objects. The XFileChooser method getSelectedXFile() is used in place of the JFileChooser method getSelectedFile().
readFromFile(), which reads from a file into the Editor, takes an XFile as an argument, and in turn calls XFileInputStream(), which is the Extended File API's equivalent to the java.lang.io method FileInputStream():
public void readFromFile(XFile file) { Document doc = jtp.getDocument(); try { XFileInputStream is = new XFileInputStream(file); String ins = retrieveAsString(is); doc.insertString(0, ins, stdoutSet); ...
The same file chooser is instantiated for both Open and Save As. This has two advantages: first, the chooser remembers the current directory between uses, so that the Open and Save As dialogue windows automatically share the same directory. Second, if you choose to customize the file chooser, you only have to customize it once; your customizations apply to both the Open and Save versions of it.
The actual dialogue box (shown in Figure 5-1) is brought up by the call to either showOpenDialog() or showSaveDialog(), both of which are inherited from JFileChooser. (APPROVE_OPTION is also inherited from JFileChooser.)