Results 1 to 5 of 5
  1. #1
    super3go is offline Member
    Join Date
    Apr 2009
    Posts
    2
    Rep Power
    0

    Default Help on Editor Program

    Hello JavaForum members! This is my first ever post to this site, and hopefully you guys can push me in the right direction.
    I am taking a course in Java, and one of my projects is to implement the open, save, copy, cut, and paste options of a barebone template of a text editor.

    I have decided to tackle open/saving first, and then the rest later.

    Here is the code I have so far (Editor.java is the main thing, EditorMenuHandler.java helps out, and SimpleFileWriter/Reader are utilized to write/read to a file respectively.)

    Editor.java

    Java Code:
    /*
     * comp285 Editor class
     */
    import java.awt.*;
    import java.awt.event.*;
    /** 
     * 
     * @author   Ian A Mason.
     * @see          CenteredFrame
     * @see          java.awt.Frame
     * @version  1.0 beta
     * @date 7/02/01
     */
    
    
    class Editor extends CenteredFrame {
        /**
         * A static flag, accessed via the class, not an instance!!
         * A boolean flag used to turn on/off error messaging to System.err.
         * This protected constant can be used by the other classes in this
         * application. You can turn it off once you think your program
         * is ready to ship!
         */
        protected static final boolean VERBOSE = true;
        /** 
         * Static data, accessed via the class, not an instance!!
         * The labels for the items in the file pulldown menu.
         * This protected constant can be used by the other classes in this
         * application. These are used by the EditorMenuHandler object to 
         * decide which item has been selected.
         */
        protected static final  String[] fileLabels = 
        { "Open ...", "Save ...", "Search ...", "Quit ..." };
        /** 
         * Static data, accessed via the class, not an instance!!
         * The labels for the items in the edit pulldown menu.
         * This protected constant can be used by the other classes in this
         * application. These are used by the EditorMenuHandler object to 
         * decide which item has been selected.
         */
        protected static final  String[] editLabels = 
        { "Cut", "Copy", "Paste"};
        /**
         * The TextArea instance textArea is the little workhorse of the editor.
         * <em>Note that it is private, and must remain so!</em> Only the editor object
         * is permitted to talk to this object.
         * @see          java.awt.TextArea
         * @see          java.awt.TextComponent
         */
        public final  TextArea     textArea = new  TextArea("", 40, 80, TextArea.SCROLLBARS_BOTH); 
        /**
         * The MenuBar instance menuBar is the toplevel widget at the top of the editor
         * that contains the pull down menus. <em>Note that it is private, and must 
         * remain so! Only the editor object is permitted to talk to this object.</em>
         * @see          java.awt.MenuBar
         */
        private final  MenuBar       menuBar = new  MenuBar();
        /**
         * The file menu is the thing that one clicks on to pull down the menu items.
         * @see          java.awt.Menu
         */
        private   final  Menu         fileMenu = new  Menu("File");
        /**
         * The items in the pull down file menu belong to this array. Its length is determined
         * by the static final array of file item labels.
         * @see          java.awt.MenuItem
         */
        private   final  MenuItem[]   fileItem = new  MenuItem[fileLabels.length];
        /**
         * The edit menu is the thing that one clicks on to pull down the menu items.
         * @see          java.awt.Menu
         */
        private final  Menu         editMenu = new  Menu("Edit");
        /**
         * The items in the pull down edit menu belong to this array. Its length is determined
         * by the static final array of edit item labels.
         * @see          java.awt.MenuItem
         */
        private final  MenuItem[]   editItem = new  MenuItem[editLabels.length];
        /**
         * This is the name we use to refer to the  object that handles the editors
         * events. Though we will not actually ever send it any messages, just merely
         * register it with Java as a listener to the appropriate events.
         * 
         * @see          EditorMenuHandler
         */
        private EditorMenuHandler menuHandler;
        /**
         * An auxiliary procedure for initializing the pull down menus. It eliminates
         * a small amount of code duplication.
         */
        private void initMenu(MenuItem[]  menuItems, 
    			  String[] menuLabels, 
    			  Menu     menu,
    			  EditorMenuHandler menuHandler,
    			  MenuBar       menuBar){
    	for(int i = 0; i < menuItems.length; i++){
    	    menuItems[i] = new MenuItem(menuLabels[i]);
    	    menu.add(menuItems[i]);
    	    menuItems[i].addActionListener(menuHandler);
    	}
    	menuBar.add(menu);
        }
        /**
         * The private Editor object constructor is where most of the work gets done.
         * Making the CenteredFrame part using the super construct (i.e by calling the
         * CenteredFrame constructor. It also makes the other 
         * important toplevel object, the menuHandler.
         * It also must make
         * all the awt components that are part of the editor: the text area, the 
         * pull down menus, and register the menuHandler with the widgets that it 
         * needs to listen to (the events that they generate).
         */
        private Editor(){
    	super("Text Editor");
    	menuHandler = new EditorMenuHandler(this);
    	textArea.setFont(new Font("SansSerif", Font.PLAIN, 15));
    	setMenuBar(menuBar);
    	// make the pull down file menu
    	initMenu(fileItem,fileLabels,fileMenu,menuHandler,menuBar);
    	// make the pull down edit menu
    	initMenu(editItem,editLabels,editMenu,menuHandler,menuBar);
    	//set the layout manager to be a BorderLayout object
    	setLayout(new BorderLayout());
    	//put the textArea in the center
    	add(textArea, BorderLayout.CENTER);
    	//validate the layout
    	validate();
    	//make the editor visible
    	setVisible(true);
        }
    	
    //This is where I implement the save/open functions. This is the important //stuff	
    	protected void saveFile(String filename){
    		SimpleFileWriter writer = SimpleFileWriter.openFileForWriting(filename);
    		if (writer == null) {
    			System.err.println("Couldn't open file!");
    			return;
    		}
    		System.out.println(textArea.getText());
    		writer.print(textArea.getText());
    		writer.close();
        }
    	
    	protected void openFile(String filename){
    		SimpleFileReader reader = SimpleFileReader.openFileForReading(filename);
    	    if (reader == null) {
    	        System.out.println("Couldn't open file!");
    	        return;
    	    }
    	    String line;
    	    while ((line = reader.readLine()) != null)
    	        System.out.println(line);
    	    reader.close();
    	}
    	
      /**
         * The main method that creates an Editor instance, and
         * thus starts the whole kit and kaboodle.
         */
        public static void main(String[] args){
    	Editor editor = new Editor();
    	//the reason this doesn't exit immediately is because
    	//this is actually a multithreaded application. The other
    	//thread sitting in the background is the <em>event handler thread</em>
        }
    }
    EditorMenuHandler.java
    Java Code:
    /* 
     * comp285 EditorMenuHandler class
     */
    import java.awt.*;
    import java.awt.event.*;
    /**
     * The EditorMenuHandler that handles the events generated by the 
     * menu of the Editor class.
     * @author   Ian A Mason.
     * @version  1.0 beta
     * @date 7/02/01
     * @see  java.awt.event.ActionListener
     * @see  java.awt.event.ItemListener
     */
    class EditorMenuHandler implements ActionListener, ItemListener {
        /**
         * This is the name of the Editor instance whose events this EditorMenuHandler instance is
         * listening to. It will need to ask it to perform certain tasks according to what 
         * type of event it hears has happened.
         */
        private Editor editor;
        /**
         * This constructs a EditorMenuHandler instance who handles the events of the
         * particular Editor instance.
         * 
         */
        protected EditorMenuHandler(Editor editor){ this.editor =  editor; }
        /**
         * This here is where all the events of interest get handled. It will be here
         * that you will have to ask  the editor to do the appropriate things.
         * @see  java.awt.event.ActionListener
         */
        public void actionPerformed(ActionEvent ae){
    	FileDialog filedialog;
    	final SearchDialog searchDialog;
    	String arg = (String)ae.getActionCommand();
    	// the Open ... case
    	if(arg.equals(Editor.fileLabels[0])){
    	    if(Editor.VERBOSE)
    		System.err.println(Editor.fileLabels[0] + 
    				   " has been selected");
    	    filedialog = new FileDialog(editor, "Open File Dialog", FileDialog.LOAD); 
    	    filedialog.show();
    	    if(Editor.VERBOSE){ 
    		System.err.println("Exited filedialog.setVisible(true);");
    		System.err.println("Open file = " + filedialog.getFile());
    		System.err.println("Open directory = " + filedialog.getDirectory());
    		editor.openFile(filedialog.getDirectory());
    	    }
    	}
    	//the Save ... case
    	if(arg.equals(Editor.fileLabels[1])){
    	    if(Editor.VERBOSE)
    		System.err.println(Editor.fileLabels[1] + 
    				   " has been selected");
    	    filedialog = new FileDialog(editor, "Save File Dialog", FileDialog.SAVE); 
    	    filedialog.show();
    	    if(Editor.VERBOSE){
    		System.err.println("Exited filedialog.setVisible(true);");
    		System.err.println("Save file = " + filedialog.getFile());
    		System.err.println("Save directory = " + filedialog.getDirectory());
    	    }
    //This is the function to save the file
    		editor.saveFile(filedialog.getFile());
    	}
    	//the Search ... case
    	if(arg.equals(Editor.fileLabels[2])){
    	    if(Editor.VERBOSE)
    		System.err.println(Editor.fileLabels[2] + 
    				   " has been selected");
    	    searchDialog = new SearchDialog(editor); 
    	    searchDialog.show();
    	    if(Editor.VERBOSE)
    		System.err.println("searchDialog.show(); has exited");
    	}
    	//the Quit ... case
    	if(arg.equals(Editor.fileLabels[3])){
    	    if(Editor.VERBOSE)
    		System.err.println(Editor.fileLabels[3] + 
    				   " has been selected");
    	    System.exit(0);
    
    	}
    	//the Cut case	
    	if(arg.equals(Editor.editLabels[0])){
    	    if(Editor.VERBOSE)
    		System.err.println(Editor.editLabels[0] + 
    				   " has been selected");
    	}
    	//the Copy case
    	if(arg.equals(Editor.editLabels[1])){
    	    if(Editor.VERBOSE)
    		System.err.println(Editor.editLabels[1] + 
    				   " has been selected");
    	}
    	//the Paste case
    	if(arg.equals(Editor.editLabels[2])){
    	    if(Editor.VERBOSE)
    		System.err.println(Editor.editLabels[2] +  
    				   " has been selected");
    	}
        }
        /**
         * This needs to be here since we need to implement the ItemListener 
         * interface
         * @see  java.awt.event.ItemListener
         */
        public void itemStateChanged(ItemEvent ie){
    	//shouldn't need to do anything here.
        }
    }
    SimpleFileWriter.java
    Java Code:
    /* comp285 SimpleFileReader.java
     */
    import java.io.*;
    /**
     * SimpleFileWriter is a small class to wrap around the usual File/PrintWriter
     * to shield you from the exception handling which we haven't yet gotten
     * to in class. 
     * <P>It has just four methods of note: one to open a new file for writing,
     * two to print or println a string to the file, and one to close the
     * the file when done. To keep it small, it does not have all the overloaded 
     * versions of print/println to accept all types, just convert to string first,
     * and then use the string-only print methods.
     * <P>Here is a simple example that shows using the SimpleFileWriter
     * to create a new file and write some text into it:
     * <PRE>
     *    SimpleFileWriter writer = SimpleFileWriter.openFileForWriting("output.txt");
     *    if (writer == null) {
     *       System.out.println("Couldn't open file!");
     *       return;
     *    }
     *    writer.print("Here is some text!");
     *    writer.println(" The year is " + 1999 + " and I feel fine.");
     *    writer.close();
     * </PRE>
     * <P>You are free to edit or extend this class, but we don't expect that
     * you should need to make any changes.
     *
     *
     * @see          java.io.FileWriter
     * @see          java.io.PrintWriter
     * @version      1.1 10/01/99
     * @author       Julie Zelenski
     */
    
    public class SimpleFileWriter 
    {
       /**
    	 * Opens a new file for writing. The filename can either be a relative
    	 * path, which will be relative to the working directory of the program
    	 * when started, or an absolute path. If the file can be created, 
    	 * a new SimpleFileWriter is returned. If the file already exists, this
    	 * will overwrite its contents. If the file cannot be
    	 * opened (for any reason: wrong name, wrong path, lack of permissions, etc.)
    	 * null is returned.
    	 */
    
    	public static SimpleFileWriter openFileForWriting(String filename)
    	{
    		try {
    			return new SimpleFileWriter(new PrintWriter(new FileWriter(filename), true));
    		} catch(IOException e) {	
    			return null;
    		}	
    	}	
    	
       /**
    	 * Appends a string to the end of the file without adding any
    	 * trailing new line. 
    	 */
    	public void print(String s)
    	{
    		writer.print(s);
    	}
    
       /**
    	 * Appends a string to the end of the file and adds a
    	 * trailing new line. 
    	 */
    	public void println(String s)
    	{
    		writer.println(s);
    	}
    	
    	
    	/**
    	 * Closes the file when done writer.  You should close a writer when
    	 * you are finished to flush its contents to disk and release the OS 
    	 * resources for use by others.
    	 */
    	public void close()
    	{
    		writer.close();
    	}
    	
    	/**
    	 * Constructor is private so that only means to create a new writer
    	 * is through the static method which does error checking.
    	 */
    	private SimpleFileWriter(PrintWriter writer) 
    	{
    		this.writer = writer;
    	}
    	
    	private PrintWriter writer;
    
    }
    and finally SimpleFileReader.java
    Java Code:
    /* comp285 SimpleFileReader.java
     */
    import java.io.*;
    /**
     * SimpleFileReader is a small class to wrap around the usual FileReader
     * to shield you from the exception handling which we haven't yet gotten
     * to in class. 
     * <P>It has just three methods of note: one to open a new file for reading,
     * one to read line from an open file, and one to close the file when done.
     * <P>Here is a simple example that shows using the SimpleFileReader to
     * to display the contents of a file on the console:
     * <PRE>
     *    SimpleFileReader reader = SimpleFileReader.openFileForReading("letter.txt");
     *    if (reader == null) {
     *        System.out.println("Couldn't open file!");
     *        return;
     *    }
     *    String line;
     *    while ((line = reader.readLine()) != null)
     *        System.out.println(line);
     *    reader.close();
     * </PRE>
     * <P>You don't need to make any changes.
     *
     *
     * @see           java.io.FileReader
     * @see          java.io.BufferedReader
     * @version      1.1 10/01/99
     * @author       Julie Zelenski
     */
    public class SimpleFileReader
    {
    
    	/**
    	 * Opens a new file for reading. The filename can either be a relative
    	 * path, which will be relative to the working directory of the program
    	 * when started, or an absolute path. If the file exists and can be
    	 * opened, a new SimpleFileReader is returned. If the file cannot be
    	 * opened (for any reason: wrong name, wrong path, lack of permissions, etc.)
    	 * null is returned.
    	 */
    	public static SimpleFileReader openFileForReading(String filename)
    	{
    		try {
    			return new SimpleFileReader(new BufferedReader(new FileReader(filename)));
    		} catch(IOException e) {	
    			return null;
    		}	
    	}
    	
    	
    	/**
    	 * Reads the next line from the open file. Returns the entire contents
    	 * of the line as one string, excluding the newline at the end.
    	 * If at EOF and no more lines to read, null is returned. null is also
    	 * returned on any I/O error.
    	 */
    	public String readLine()
    	{
    		try {
    			return reader.readLine();
    		} catch (IOException e) {
    			return null;
    		}
    	}
    
    	/**
    	 * Closes the file when done reading.  You should close a reader when
    	 * you are finished to release the OS resources for use by others.
    	 */
    	public void close()
    	{
    		try {
    			reader.close();
    		} catch (IOException e) {}
    	}
    	
    	/**
    	 * Constructor is private so that only means to create a new reader
    	 * is through the static method which does error checking.
    	 */
    	private SimpleFileReader(BufferedReader reader) 
    	{
    		this.reader = reader;
    	}
    	
    	private BufferedReader reader;
    
    }
    Note that I don't need to change anything in these final 2 classes, only Editor and EditorMenuHandler.

    My problem is that the Save function doesn't create a .txt file and save the contents into it. It reads the textArea contents perfectly but something is missing for the saving.

    For opening the file, the console would simply output "Couldn't open file!"

    So what essentially I am asking is, how do you create a new file to print text in and save, and same thing for opening, to edit it?

    Thank you for your time.

  2. #2
    tghn2b is offline Member
    Join Date
    Jan 2008
    Posts
    31
    Rep Power
    0

    Default

    Hi I tried to make a Editor.class and I got a lot of errors
    Java Code:
    Editor.java:16: cannot find symbol
    symbol: class CenteredFrame
    class Editor extends CenteredFrame {
                         ^
    Editor.java:118: cannot find symbol
    symbol  : method setMenuBar(java.awt.MenuBar)
    location: class Editor
    	setMenuBar(menuBar);
            ^
    Editor.java:124: cannot find symbol
    symbol  : method setLayout(java.awt.BorderLayout)
    location: class Editor
    	setLayout(new BorderLayout());
            ^
    Editor.java:126: cannot find symbol
    symbol  : method add(java.awt.TextArea,java.lang.String)
    location: class Editor
    	add(textArea, BorderLayout.CENTER);
            ^
    Editor.java:128: cannot find symbol
    symbol  : method validate()
    location: class Editor
    	validate();
            ^
    Editor.java:130: cannot find symbol
    symbol  : method setVisible(boolean)
    location: class Editor
    	setVisible(true);
            ^
    Editor.java:135: cannot find symbol
    symbol  : class SimpleFileWriter
    location: class Editor
    		SimpleFileWriter writer = SimpleFileWriter.openFileForWriting(filename);
                    ^
    Editor.java:135: cannot find symbol
    symbol  : variable SimpleFileWriter
    location: class Editor
    		SimpleFileWriter writer = SimpleFileWriter.openFileForWriting(filename);
                                              ^
    .\EditorMenuHandler.java:35: cannot find symbol
    symbol  : class SearchDialog
    location: class EditorMenuHandler
    	final SearchDialog searchDialog;
                  ^
    .\EditorMenuHandler.java:42: cannot find symbol
    symbol  : constructor FileDialog(Editor,java.lang.String,int)
    location: class java.awt.FileDialog
    	    filedialog = new FileDialog(editor, "Open File Dialog", FileDialog.LOAD); 
                             ^
    .\EditorMenuHandler.java:56: cannot find symbol
    symbol  : constructor FileDialog(Editor,java.lang.String,int)
    location: class java.awt.FileDialog
    	    filedialog = new FileDialog(editor, "Save File Dialog", FileDialog.SAVE); 
                             ^
    .\EditorMenuHandler.java:71: cannot find symbol
    symbol  : class SearchDialog
    location: class EditorMenuHandler
    	    searchDialog = new SearchDialog(editor); 
                                   ^
    Note: .\EditorMenuHandler.java uses or overrides a deprecated API.
    Note: Recompile with -Xlint:deprecation for details.
    12 errors

  3. #3
    xcallmejudasx's Avatar
    xcallmejudasx is offline Senior Member
    Join Date
    Oct 2008
    Location
    Houston, TX & Flint, MI
    Posts
    609
    Rep Power
    6

    Default

    I just glanced over your open/save method but something you might want to try is a check to determine if a File exists under the name you've supplied and if not actually create a new File(fileName) somewhere within your code.
    Liberty has never come from the government.
    Liberty has always come from the subjects of government.
    The history of liberty is the history of resistance.
    The history of liberty is a history of the limitation of governmental power, not the increase of it.

  4. #4
    super3go is offline Member
    Join Date
    Apr 2009
    Posts
    2
    Rep Power
    0

    Default

    tghn2b:

    There is another couple of classes which I did not include because they aren't necessary for editing, CenteredFrame.java (which creates the window in the center of your screen) and SearchDialog.java (which is used for the Search option in the editor).

    Here they are though:
    Centered Frame:
    Java Code:
    /* comp285 CenteredFrame.java
     */
    import java.awt.*;
    
    /**
     * CenteredFrame is a simple subclass of Frame that uses the
     * Toolkit to center the frame in the middle of the screen, 
     * and sizes it to be half the height and width of the screen.
     * @see          java.awt.Toolkit
     * @see          java.awt.Frame
     * @version      1.0 beta 
     * @author       Ian A Mason
     */
    
    public class CenteredFrame extends Frame{
        /**
         * The CenteredFrame contructor, contructs an initially 
         * invisible frame, it uses the Toolkit to center the 
         * frame in the middle of the screen, and size
         * it to be half the height and width of the screen.
         */
         public CenteredFrame(String title){
    	 super(title);
    	 Dimension d = 
    	     Toolkit.getDefaultToolkit().getScreenSize();
    	 int screenH = d.height;
    	 int screenW = d.width;
    	 setSize(screenW/2, screenH/2);
    	 setLocation(screenW/4, screenH/4);
         }
    
        /**
         *  For testing, constructs a CenteredFrame object 
         *  and then makes it visible.
         */
         public static void main(String[] args) {
    	 CenteredFrame f = new CenteredFrame("Centered Frame");
    	 f.setVisible(true);
         }
         
         
     }
    SearchDialog.java
    Java Code:
    /* 
     * comp285  SearchDialog Widget
     */
    import java.awt.*;
    import java.awt.event.*;
    /** 
     * This here widget is used by the EditMenuHandler, come back now, ya hear!
     * @author   Ian A Mason.
     * @version  1.0 beta
     * @date 8/03/01
     * @see  java.awt.Dialog
     */
    public class SearchDialog extends Dialog {
        /** 
         * 
         * @see  java.awt.TextField
         */
        private final TextField target  = new TextField(12);
        /** 
         * 
         * @see  java.awt.Button
         */
        private Button button = new Button("Search File");
        /** 
         * 
         */
        protected String getText(){  return target.getText(); }
        /** 
         * 
         */
        protected  SearchDialog(Editor editor){
    	super(editor, "Search Dialog", true); 
    	setLayout(new FlowLayout());
    	button.setFont(new Font("SansSerif", Font.PLAIN, 20));
    	button.setForeground(Color.red);
    	add(button);
    	Label label = new Label("String: ", Label.CENTER);
    	label.setFont(new Font("SansSerif", Font.PLAIN, 20));
    	add(label);
    	target.setFont(new Font("SansSerif", Font.PLAIN, 15));
    	add(target); 
    	Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
    	int screenH = d.height;
    	int screenW = d.width;
    	setSize(screenW/3, screenH/8);
    	setLocation(screenW/2, screenH/2);
    	pack();
    	button.addActionListener(new ActionListener(){
    		public void actionPerformed(ActionEvent ae){
    		    if(Editor.VERBOSE)
    			System.out.println("Shutting down dialog " +
    					   "(terminatining call to dialog.show();");
    		    //disposes  the Dialog and then causes its show() 
    		    //to return if it is currently blocked.
    		    SearchDialog.this.dispose();
    		    if(Editor.VERBOSE)
    			System.out.println("String to be searched for = " +
    					   target.getText());
    		}
    	    });
        }
    }

  5. #5
    Join Date
    Mar 2009
    Posts
    25
    Rep Power
    0

    Default

    Take a look at the java.io.File class in the Java API (google search File class java 6 and it'll be the first link)
    In particular look at the exists() and createNewFile() methods of the File class.

Similar Threads

  1. Editor for Java
    By peiceonly in forum New To Java
    Replies: 4
    Last Post: 08-13-2008, 08:27 AM
  2. oXygen XML editor 9.3
    By Java Tip in forum Java Software
    Replies: 0
    Last Post: 07-11-2008, 02:47 PM
  3. Sketsa SVG Editor 5.3
    By Java Tip in forum Java Software
    Replies: 0
    Last Post: 07-11-2008, 02:38 PM
  4. SWT Text Editor
    By Java Tip in forum SWT
    Replies: 0
    Last Post: 07-07-2008, 04:43 PM
  5. Xml Editor
    By Marty in forum XML
    Replies: 3
    Last Post: 05-11-2007, 09:27 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •