7 Replies - 3273 Views - Last Post: 05 September 2012 - 08:49 PM Rate Topic: -----

#1 Regamus  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 25-August 12

Java Text Editor-Open, Save, Search

Posted 02 September 2012 - 03:44 PM

Hi, I'm trying to construct a simple text editor that has the following options: Open, Save, Search, Cut, Copy, Paste, and Quit. Out of these, I've managed to complete the Cut, Copy, Paste, and Quit options. I'm having some difficulty on the Open, Save, and Search options, however, and I would greatly appreciate any help.

1) Open - I press the Open Button, and it gives the file dialog, but upon choosing a file, absolutely nothing happens (aside from the file dialog closing).

2) Save - I press the Save Button, and a File does save, but since I can't open it again, I can't confirm whether the text saved alright or not (however, I currently suspect it didn't).

3) Search - I press the Search Button, and it seems like everything is working, but say, if the string "Hat" showed up three times in a file, the Search function would only take me to the first string.

Here is my code:

Editor Class:

/*
 * comp285 Editor class
 */
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/** 
 * 
 * @author   Ian A Mason.
 * @see          CenteredFrame
 * @see          java.awt.Frame
 * @version  1.0 beta 9/24/10
 */


public class Editor extends CenteredFrame {
	private static final long serialVersionUID = 2549009292395922530L;
	/**
     * 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
     */
    private 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);
    }
    /**
     * 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();
	editor.setVisible(true);
	//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>
    }
        public void Open(String name){  
        	BufferedReader reader = null;
        	try
        	{
        		reader = new BufferedReader( new FileReader( name));
        		reader.read();
        	}
        	catch ( IOException e)
        	{
        	}
        	finally
        	{
        		try
        		{
        			if (reader != null)
        				reader.close();
        		}
        		catch (IOException e)
        		{        			
        		}
        	}
   }  
    
    public void Save(String name){  
        BufferedWriter writer = null; 
        try 
        { 
                writer = new BufferedWriter( new FileWriter( name)); 
                writer.write( name); 
 
        } 
        catch ( IOException e) 
        { 
        } 
        finally 
        { 
                try 
                { 
                        if ( writer != null) 
                                writer.close( ); 
                } 
                catch ( IOException e) 
                { 
                } 
        }
     } 
 



	public void Search(SearchDialog searcher){  
     String theText= searcher.getText();  
     if (theText=="") {  
         System.err.println("Nothing to search");  
         return;  
     }  
      String content = textArea.getText();  
     int index = content.indexOf(theText, 0);  
    if (index >= 0) {   // match found  
         int newlines=0;  
        textArea.select(0, index);  
         String simple= textArea.getSelectedText();  
        char str[]=simple.toCharArray();  
         for(int i=0; i<simple.length(); i++){  
             if(str[i]=='\n'){  
                newlines+=1;  
             }  
        }  
        index=index-newlines;      
        int end = index + theText.length();  
             textArea.select(index,end);  
             searcher.setBackground(Color.YELLOW);  
         }  
     else {  
         searcher.setBackground(Color.RED);  
        System.err.println("'" + theText + "' not found.");  
    }  
 } 

	   public void Cut(Clipboard clipboard){  
        String selection = textArea.getSelectedText();  
      StringSelection data = new StringSelection(selection);  
         clipboard.setContents(data, data);  
       textArea.replaceRange("", textArea.getSelectionstart(), textArea.getSelectionend());  
 }  

    public void Copy(Clipboard clipboard){  
       String selection = textArea.getSelectedText();  
        StringSelection data = new StringSelection(selection);  
      clipboard.setContents(data, data);    
 }  

    public void Paste(Transferable clipData){  
        if (clipData != null) {  
             try {  
              if  
                 (clipData.isDataFlavorSupported  
                     (DataFlavor.stringFlavor)) {  
                     String s = (String)(clipData.getTransferData(  
                      DataFlavor.stringFlavor));  
                    textArea.replaceRange("", textArea.getSelectionstart(), textArea.getSelectionend());  
                    textArea.insert(s, textArea.getCaretPosition());  
              }  
                    
           } catch (UnsupportedFlavorException ufe) {  
               System.err.println("Flavor unsupported: " + ufe);  
            } catch (IOException ioe) {  
            System.err.println("Data not available: " + ioe);  
 }  
}  
 }
}



EditorMenuHandler Class:
/*   

  * comp285 EditorMenuHandler class  

  */ 

import java.awt.*;  
import java.awt.event.*;  
import java.awt.datatransfer.*;  

    

 /**  

  * 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 {  

       int value;   

        int option;   

        String content = null;   

        String name = null;   

        String word;   

       String str;  

   

     /**  

      * 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  

      */ 

     @SuppressWarnings("deprecation")  

     public void actionPerformed(ActionEvent ae){  

     FileDialog filedialog;  

     final Clipboard clipboard = editor.getToolkit().getSystemClipboard();  

     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.Open(filedialog.getDirectory()+filedialog.getFile());
       }  
    }  

     //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());  
    
         editor.Save(filedialog.getDirectory()+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");  
           
        editor.Search(searchDialog);  

     }  

        
     //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");  
         editor.Cut(clipboard);  
    }  
     //the Copy case  
     if(arg.equals(Editor.editLabels[1])){  
         if(Editor.VERBOSE)  
         System.err.println(Editor.editLabels[1] +   
                    " has been selected");  
            
         editor.Copy(clipboard);  
     }  
     //the Paste case  
     if(arg.equals(Editor.editLabels[2])){  
         if(Editor.VERBOSE)  
         System.err.println(Editor.editLabels[2] +    
                    " has been selected");  
         Transferable clipData = clipboard.getContents(clipboard);  
         editor.Paste(clipData);  

     } 
} 

     /**  

      * 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.  

     }  

 } 


These classes and these classes alone can be modified.
-----------------------------------------------------------------------------------------------------------------------
SearchDialog Class:
/* 
 * 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 9/24/10
 * @see  java.awt.Dialog
 */
public class SearchDialog extends Dialog {
	private static final long serialVersionUID = -8306136873175102207L;
	/** 
     * 
     * @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());
		}
	    });
    }
}



CenteredFrame Class:
/* 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 9/24/10
 * @author       Ian A Mason
 */

public class CenteredFrame extends Frame{
	private static final long serialVersionUID = 559879839348634376L;

	/**
     * 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);
     }
     
     
 }



SimpleFileReader Class:
/* 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;

}




SimpleFileWriter Class:
/* 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;

}



These classes are given and required to run the program, but are not allowed to be modified.


Thank you very much for any and all help!

Is This A Good Question/Topic? 0
  • +

Replies To: Java Text Editor-Open, Save, Search

#2 Regamus  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 25-August 12

Re: Java Text Editor-Open, Save, Search

Posted 03 September 2012 - 04:43 PM

Sorry, I just realized how much code I just spat at you guys, so to make things a bit easier for you guys to read:

Open:
        public void Open(String name){  
        	BufferedReader reader = null;
        	try
        	{
        		reader = new BufferedReader( new FileReader( name));
        		reader.read();
        	}
        	catch ( IOException e)
        	{
        	}
        	finally
        	{
        		try
        		{
        			if (reader != null)
        				reader.close();
        		}
        		catch (IOException e)
        		{        			
        		}
        	}
   }  



Save:
        public void Save(String name){  
    BufferedWriter writer = null; 
    try 
    { 
            writer = new BufferedWriter( new FileWriter(name)); 
            writer.write(name); 

    } 
    catch ( IOException e) 
    { 
    } 
    finally 
    { 
            try 
            { 
                    if ( writer != null) 
                            writer.close( ); 
            } 
            catch ( IOException e) 
            { 
            } 
    }
 }



Search
	public void Search(SearchDialog searcher){  
     String theText= searcher.getText();  
     if (theText=="") {  
         System.err.println("Nothing to search");  
         return;  
     }  
      String content = textArea.getText();  
     int index = content.indexOf(theText, 0);  
    if (index >= 0) {   // match found  
         int newlines=0;  
        textArea.select(0, index);  
         String simple= textArea.getSelectedText();  
        char str[]=simple.toCharArray();  
         for(int i=0; i<simple.length(); i++){  
             if(str[i]=='\n'){  
                newlines+=1;  
             }  
        }  
        index=index-newlines;      
        int end = index + theText.length();  
             textArea.select(index,end);  
             searcher.setBackground(Color.YELLOW);  
         }  
     else {  
         searcher.setBackground(Color.RED);  
        System.err.println("'" + theText + "' not found.");  
    }  
 } 




All three snippets are taken straight from the Editor class.

Thanks!
Was This Post Helpful? 0
  • +
  • -

#3 Sheph  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 432
  • View blog
  • Posts: 1,020
  • Joined: 12-October 11

Re: Java Text Editor-Open, Save, Search

Posted 03 September 2012 - 06:20 PM

How are these Open, Save, Cut methods called? You'll need access to the TextArea so you can read/write the data from/to the right place.

Also, try to respect Java conventions on naming your methods. methods start with a lowercase letter for the first word. When I see Open() I think constructor, or class and it can be confusing.
Was This Post Helpful? 2
  • +
  • -

#4 Regamus  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 25-August 12

Re: Java Text Editor-Open, Save, Search

Posted 03 September 2012 - 06:40 PM

They're called by the EditorMenuHandler class above, and these snippets show exactly where:

     // 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.Open(filedialog.getDirectory()+filedialog.getFile());
       }  
    }  



    //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());  
    
         editor.Save(filedialog.getDirectory()+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");  
           
        editor.Search(searchDialog);  

     } 




Sorry about the naming thing, I'll do that from now on.
Was This Post Helpful? 0
  • +
  • -

#5 Sheph  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 432
  • View blog
  • Posts: 1,020
  • Joined: 12-October 11

Re: Java Text Editor-Open, Save, Search

Posted 03 September 2012 - 08:53 PM

Inside each of those methods, you will need to access the TextArea. If you are opening, you have to textArea.append( line ), for each line in the file, etc.
Was This Post Helpful? 0
  • +
  • -

#6 Regamus  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 25-August 12

Re: Java Text Editor-Open, Save, Search

Posted 03 September 2012 - 09:55 PM

Thanks, that definitely puts me on the right track! However, I don't think I've implemented the "textArea" stuff correctly. Here are the modified methods:

Open
        public void Open(String name){  
        	BufferedReader reader = null;
        	try
        	{
        		reader = new BufferedReader( new FileReader( name));
        		reader.read();
                StringBuffer text = new StringBuffer() ;  
                while( ( name = reader.readLine() ) != null )   
                {  
                   text.append( name ).append( "\n" ) ;  
                }  
                textArea.setText( text.toString() ) ;             
        	}
        	catch ( IOException e)
        	{
        	}
        	finally
        	{
        		try
        		{
        			if (reader != null)
        				reader.close();
        		}
        		catch (IOException e)
        		{        			
        		}
        	}
   } 



Save:
        public void Save(String name){  
    BufferedWriter writer = null; 
    try 
    { 
            writer = new BufferedWriter( new FileWriter(name)); 
            writer.write(name); 
            StringBuffer text = new StringBuffer();
            while( ( name = writer.write() ) != null )   
            {  
               text.append( name ).append( "\n" ) ;  
            }  
            textArea.setText( text.toString() ) ;             
    } 
    catch ( IOException e) 
    { 
    } 
    finally 
    { 
            try 
            { 
                    if ( writer != null) 
                            writer.close( ); 
            } 
            catch ( IOException e) 
            { 
            } 
    }
 } 



Alright, so Open now displays the file name as opposed to the text inside, and if no file name is selected, it displays "null" (like it prints the word out on the screen). Save... well it no longer even saves the file now.

Also, if anybody has any ideas concerning the Search issue, that would help as well.

Thanks!
Was This Post Helpful? 0
  • +
  • -

#7 Regamus  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 25-August 12

Re: Java Text Editor-Open, Save, Search

Posted 04 September 2012 - 08:59 PM

Okay, so after a few tutorials into textArea, I managed to get it working...with one MAJOR problem. Lemme post the updated code first.

Open
    public void Open(String name){    
    	File textFile = new File(name + ".txt.");
          BufferedReader reader = null;  
          try 
          {  
        	 textArea.append(x);
             reader = new BufferedReader( new FileReader( textFile));  
             reader.read();  
         }  
          catch ( IOException e)  
          {  
         }  
          finally 
         {  
             try 
              {  
                 if (reader != null)  
                     reader.close();  
             }  
            catch (IOException e)  
             {                     
             }  
         }  
 } 



Save
    public void Save(String name){   
	File textFile = new File(name + ".txt");
BufferedWriter writer = null;   
try  
{   
        writer = new BufferedWriter( new FileWriter(textFile));   
        writer.write(name);
        x = textArea.getText();

}   
catch ( IOException e)   
{   
}   
finally  
{   
       try  
      {   
               if ( writer != null)   
                        writer.close( );   
       }   
        catch ( IOException e)   
        {   
       }   
}  
} 



Search
	public void Search(SearchDialog searcher){  
     String theText= searcher.getText();  
     if (theText=="") {  
         System.err.println("Nothing to search");  
         return;  
     }  
      String content = textArea.getText();  
     int index = content.indexOf(theText, 0);  
    if (index >= 0) {   // match found  
         int newlines=0;  
        textArea.select(0, index);  
         String simple= textArea.getSelectedText();  
        char str[]=simple.toCharArray();  
         for(int i=0; i<simple.length(); i++){  
             if(str[i]=='\n'){  
                newlines+=1;  
             }  
        }  
        index=index-newlines;      
        int end = index + theText.length();  
             textArea.select(index,end);  
             searcher.setBackground(Color.YELLOW);  
         }  
     else {  
         searcher.setBackground(Color.RED);  
        System.err.println("'" + theText + "' not found.");  
    }  
 } 




Okay, so here are my problems as of right now:

1)So, while Save and Open do indeed save text in a file and redisplay that text respectively, it will only do so if you saved that file the same time you ran that application. For example, if I ran the program, saved a file called Red with the text "Blue" typed into it, closed the program, ran the program again, then opened Red, it wouldn't show "Blue".

2)Search...just like before, I have absolutely no idea how to fix it (same problem as before)...perhaps a for loop?

Thanks!
Was This Post Helpful? 0
  • +
  • -

#8 Regamus  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 19
  • Joined: 25-August 12

Re: Java Text Editor-Open, Save, Search

Posted 05 September 2012 - 08:49 PM

I do have some solutions in my mind, however, I don't fully understand them, and can't really implement them, so I thought I'd ask you guys!

Code: The code hasn't changed (I did add file i/o streams, but took them out after it failed).


1)Okay, so from what I understand, my problem is that since I'm using a string to hold the text in the textArea, that string isn't getting saved into the file. Could somebody please suggest a way to SAVE the contents of the string into the file (as in, the string can be written over and the file will still have the text)? I tried streams, but they didn't work, so I don't know how else to do it (vectors, FileUtils?)


2) For search (no changes to code), I think that something is causing the searchDialog to close after using the search function once. However, I don't know what. Could somebody please help me out here?

3)Alright, so I've actually discovered another problem with the Open method: Upon closing the method without opening a file, it will display the string x (in other words, what ever I last typed). I have no idea why that's happening... did I misplace anything in that method? I've tried shifting stuff around (specifically the textArea.append(x) line), but to no avail. Any advice here...?


THANKS!
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1