//======================================================================//  PROJECT:            _programming.java_//  FILE:               WordPro.java//  PURPOSE:            Chapter 10 lablet//  VERSION:            2.0//  TARGET:             Java v1.1//  UPDATE HISTORY:     2.0     12/2/98    1.1 event model, menu shortcuts//                      1.0     7/19/97    the version in _p.j_//======================================================================//------------------------------- NOTES --------------------------------/*   This is an application, rather than an applet, for three reasons.   First, we want to control the action of this program by menus   and there's no easy way to attach menus to applets.  Second,   we want to be able to save our text to a file and applets   have very restricted access to the computer's file system, not only   because of built-in security considerations but also because of   extra restrictions placed on them by some browsers.  Finally, we   wanted to give you some experience with Java applications, in   addition to all of the practice with applets you've had so far.  *///------------------------------ IMPORTS -------------------------------import java.awt.*;import java.awt.event.*;import java.io.*;         // for file support  //=========================== WordPro CLASS ============================/** * A WordPro object is a frame that is to be used in a word-processing  * application. It contains the customary File and Edit menus, a TextArea * to hold the text, and a TextField to display status messages. */public class WordPro extends Frame implements ActionListener{    private String    clipBoard = new String();    private String    fileName  = new String();    private TextArea  text      = new TextArea(20,80);    private TextField display   = new TextField(15);     public WordPro()    {        setTitle("p.j WordPro");        MenuBar mbar = new MenuBar();        // Define and add the File menu to the menu bar.                Menu mf = new Menu("File");        mf.add(new MenuItem("New"));        mf.add(new MenuItem("Open..."));        mf.add(new MenuItem("Close"));        // not implemented        mf.addSeparator();        mf.add(new MenuItem("Save"));        mf.add(new MenuItem("Save As..."));   // not implemented        mf.addSeparator();        mf.add(new MenuItem("Quit", new MenuShortcut(KeyEvent.VK_Q)));                  mbar.add(mf);                  // Define and add the Edit menu to the menu bar.                Menu med = new Menu("Edit");        med.add(new MenuItem("Cut"));        med.add(new MenuItem("Copy"));        med.add(new MenuItem("Paste"));        med.add(new MenuItem("Clear"));        mbar.add(med);          // Attach the menu bar and add the text area and display         // to our frame.  Remember, frames use Border layout.                setMenuBar(mbar);        add("South", display);        add("Center", text);                // Register the two menus as sources of action events and        // register the application as a source of window events,        // to be handled by our member class WindowMinder, defined below.		        mf.addActionListener(this);        med.addActionListener(this);        addWindowListener(new WindowMinder(this));     }          //------------------------- Event Handling -------------------------        /**     * Send all menu item events out to be processed.     */    public void actionPerformed(ActionEvent e)    {        String itemText = e.getActionCommand();        if (itemText.equals("Quit"))        {            this.dispose();            System.exit(0);        }        else if (itemText.equals("New"))        {            clearText();            fileName = "";        }        else if (itemText.equals("Open..."))        {            doOpen();        }        else if (itemText.equals("Save"))        {            doSave();        }        else if (itemText.equals("Cut"))        {            doCopy();            doClear();        }        else if (itemText.equals("Copy"))        {            doCopy();        }        else if (itemText.equals("Paste"))        {	            doPaste();        }        else if (itemText.equals("Clear"))        {            doClear();        }    }        /**     * A member class to handle WINDOW_CLOSING events. We subclass     * WindowAdapter here so we don't have to implement all     * seven of the windowListener methods.     */    private class WindowMinder extends WindowAdapter    {    	private Window owner;    	    	/**    	 * Construct a new WindowMinder object by recording    	 * a reference to the application to which it belongs.    	 */    	public WindowMinder(Window theWindow)    	{    		owner = theWindow;    	}    	    	/**    	 * Handle a request by the user to close the application's    	 * window by freeing up the window's resources and quitting.    	 */        public void windowClosing(WindowEvent e)        {        	if (e.getSource() == owner)        	{        		owner.dispose();            	System.exit(0);            }        }    }	    //------------------------ File Operations -------------------------     /**     * Display a file dialog box to allow the user to specify an     * input file, then read characters from the file, and copy     * them into the application's TextArea.     */    private void doOpen()    {        FileDialog myFD = new FileDialog(this,"Open...", FileDialog.LOAD);        myFD.show();                // Get the file name chosen by the user.                String name = myFD.getFile();        String dir = myFD.getDirectory();        fileName = dir + File.separator + name;        if (name == null)        {            // User canceled the open dialog, so return without doing anything.            display.setText("Open operation cancelled");            return;        }		        // Now we know we can open the file and copy it to the text area.        clearText();        try        {            // Create an input stream and attach it to the             // chosen file.                        FileInputStream fis = new FileInputStream(fileName);            DataInputStream inStream = new DataInputStream(fis);            // Read from the file one line at a time.                        String textLine = inStream.readLine();            int charsRead = 0;            while (textLine != null)            {                text.appendText(textLine + '\n');                charsRead += textLine.length() + 1;                textLine = inStream.readLine();            }            inStream.close();            display.setText(charsRead + " chars read from " + fileName);        }         catch (IOException e)         {            display.setText("" + e);            return;        }    }	    /**     * Copy the contents of the TextArea into a file.     */    private void doSave()    {        // If we don't have a file name, get one.        if (fileName.equals(""))        {            FileDialog myFD = new FileDialog(this,"Save as...", FileDialog.SAVE);            myFD.show();                        // Get the file name chosen by the user.                        String name = myFD.getFile();            String dir = myFD.getDirectory();            fileName = dir + File.separator + name;            if (name == null)            {                // User canceled the save dialog, so return without doing anything.                display.setText("Save operation cancelled");                return;            }        }		        String theText = text.getText();        try        {            // Create an output stream and attach it to the chosen file                        FileOutputStream fos = new FileOutputStream(fileName);            DataOutputStream outStream = new DataOutputStream(fos);            // Write the entire contents of the text to the file.                        outStream.writeBytes(theText);            outStream.close();            display.setText(theText.length() + " chars written to " + fileName);        }        catch (IOException e)        {             display.setText("" + e);            return;        }    }     /**     * Empty the text area.     */    private void clearText()    {           text.setText("");    }	    //------------------------ Edit Operations -------------------------    /**     * Place the current selection on the clipboard.     */    private void doCopy()    {                clipBoard = new String(text.getSelectedText());    }       /**     * Replace the current selection with the contents of     * the clipboard.     */    private void doPaste()    {              text.replaceText(clipBoard, text.getSelectionStart(),                         text.getSelectionEnd());    }    /**     * To delete a selected portion of text, we get the      * following strings:     *	 s1: the part before the selection     *	 s2: the part after the selection     * and then we simply set the text to be s1 + s2.     */    private void doClear()    {                // String "all" holds our text temporarily so that we can         // operate on it.                String all = new String(text.getText());        String s1 = new String(all.substring(0,text.getSelectionStart()));        String s2 = new String(all.substring(text.getSelectionEnd()));        text.setText(s1 + s2);    }	    //--------------- The Necessary Application Method -----------------     /**     * Every Java program begins its work with a call to main().     * In applets, the main() function is hidden behind the scenes in the     * runtime environment, but in an application we have to provide     * one of our own.     */    public static void main(String args[])    {        Frame myFrame = new WordPro();        myFrame.setSize(400,300);        myFrame.show();    }}