Text Editor - Save

is it sad that I can't save. Methinks so.

Page 1 of 1

3 Replies - 3877 Views - Last Post: 21 March 2010 - 07:46 PM Rate Topic: -----

#1 hawkysu  Icon User is offline

  • I am a spoon
  • member icon

Reputation: 5
  • View blog
  • Posts: 1,432
  • Joined: 20-February 09

Text Editor - Save

Posted 21 March 2010 - 07:04 PM

Hiya again Dogstopper and the rest, ;)

Anyways, I'm almost done with the basics of this. The thing is, I'm horrible at i/o and really, I don't even know where to start. So, basically, this should work like almost any save function in existence. You hit the pretty lil' button labeled save, and then it opens a box. That part is already handled. It also needs to either create a new file if their isn't one with the given name, or replace the selected file.

Sadly, it does neither of these last two things.
So, here's teh codez
/*
 * comp285 Editor class
 */
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.io.*;
import javax.swing.*;
import javax.swing.text.*;
import javax.swing.event.*;
import javax.swing.GroupLayout.*;


/** 
 * 
 * @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
     */
    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();
	//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>
    }
    
    /**
     * Like all good Open functions, the Open method opens a selected file.
     * @param name
     */
    public void Open(String name){
    	SimpleFileReader read= SimpleFileReader.openFileForReading(name);
		if(read == null){
			System.out.println("Couldn't Open File");
			return;
		}
    	textArea.setText("");
		while(read.readLine()!=null){
    	textArea.append(read.readLine());
    	textArea.append("\n");
    	}
    	read.close();
    	
    }
    
    /**
     * The Save method Saves stuff.... or it will when i feex eet.
     * @param name
     */
    public void Save(String name){
    	SimpleFileWriter write= SimpleFileWriter.openFileForWriting(name);
    	if(write==null) return;
    	while(textArea.getText()!=null){
    		write.print(textArea.getText());
    	}
    	write.close();
    }
    
    /**
     * Search will bring up the search dialog box and read the text inputed by the user when the
     * user presses the button. Then it will pull up the first occurrence of the word and highlight it.
     * This can be useful if you're trying to search for a word you want to change or a word you think you
     * spelled wrong.
     * @param searcher
     */
    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.");
        }
    }
    
    /**
     * Copy is reads the highlighted text and places it on the clipboard. This allows
     * the user to use string multiple times without retyping it, or to place the string
     * in another text box.
     * @param clipboard
     */
    public void Copy(Clipboard clipboard){
    	String selection = textArea.getSelectedText();
        StringSelection data = new StringSelection(selection);
        clipboard.setContents(data, data);

    }
    
    /**
     * Paste is the opposite of copy. It takes the string from a clipboard and places it into where the
     * cursor is set. If there is highlighted texr, paste will replace it.
     * @param clipData
     */
    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);
            }
          }
        }

    /**
     * Cut is another way to copy a string. The exception is, cut deletes the highlighted text from a textbox.
     * If the user wanted to move some text around, they'd cut it and then paste it.
     * i.e. "Tom From" can become "From Tom" by cutting the "From" and Pasting it in front of
     * "Tom."
     * @param clipboard
     */
    public void Cut(Clipboard clipboard){
    	String selection = textArea.getSelectedText();
        StringSelection data = new StringSelection(selection);
        clipboard.setContents(data, data);
        textArea.replaceRange("", textArea.getSelectionstart(), textArea.getSelectionend());
    }
}


And for easy reference:
    /**
     * The Save method Saves stuff.... or it will when i feex eet.
     * @param name
     */
    public void Save(String name){
    	SimpleFileWriter write= SimpleFileWriter.openFileForWriting(name);
    	if(write==null) return;
    	while(textArea.getText()!=null){
    		write.print(textArea.getText());
    	}
    	write.close();
    }



And then the class that calls to all of the stuffits:
/* 
 * comp285 EditorMenuHandler class
 */
import java.awt.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.io.*;

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



------
Hopefully this won't be too bad. It's mainly just my lack of understanding.
Thanks~

This post has been edited by Dogstopper: 21 March 2010 - 07:08 PM
Reason for edit:: fixed teh tagez


Is This A Good Question/Topic? 0
  • +

Replies To: Text Editor - Save

#2 Dogstopper  Icon User is offline

  • The Ninjaducky
  • member icon



Reputation: 2870
  • View blog
  • Posts: 11,021
  • Joined: 15-July 08

Re: Text Editor - Save

Posted 21 March 2010 - 07:12 PM

Actually, you can accomplish most of this rather easily using JOptionPane. Why don't you take a look at it. It allows to pick a file or filename (type it into the box) and either save a new file or overwrite - exactly what you're looking for...

http://java.sun.com/...ilechooser.html
Was This Post Helpful? 0
  • +
  • -

#3 hawkysu  Icon User is offline

  • I am a spoon
  • member icon

Reputation: 5
  • View blog
  • Posts: 1,432
  • Joined: 20-February 09

Re: Text Editor - Save

Posted 21 March 2010 - 07:21 PM

Hmm, Well, I'll definitely try it and get back to you. But I'm not sure if we are allowed to us JStuff since one of the requirements is "minimal change to my code."

That said, I'll try it first.
Thanks.

Edit:

By the way, did I say i'd try it first? >_>
repetition, IT BURNS

Edit 2:
XD I forgot to add this in the message above:
It might be kinda important...
SimpleFileWriter.java
/* 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;

}




I am not organized tonight :/

This post has been edited by hawkysu: 21 March 2010 - 07:28 PM

Was This Post Helpful? 0
  • +
  • -

#4 hawkysu  Icon User is offline

  • I am a spoon
  • member icon

Reputation: 5
  • View blog
  • Posts: 1,432
  • Joined: 20-February 09

Re: Text Editor - Save

Posted 21 March 2010 - 07:46 PM

Ok, So I e-mailed my teacher and she said:
"It is strongly discouraged that you use that."
Which doesn't translate well in my opinion.

Also, I returned it to how I originally had it and came across something interesting.
It creates a file with that name, however, it cannot open those files. And also, after I use the save feature, all the buttons stop working and I have to ctrl+alt+delete my way to safety :/

Also, the list of errors I get when I tried to open a File that this editor saved is:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: null string
at sun.awt.windows.WTextAreaPeer.insertText(Native Method)
at java.awt.TextArea.insertText(Unknown Source)
at java.awt.TextArea.appendText(Unknown Source)
at java.awt.TextArea.append(Unknown Source)
at Editor.Open(Editor.java:167)
at EditorMenuHandler.actionPerformed(EditorMenuHandler.java:62)
at java.awt.MenuItem.processActionEvent(Unknown Source)
at java.awt.MenuItem.processEvent(Unknown Source)
at java.awt.MenuComponent.dispatchEventImpl(Unknown Source)
at java.awt.MenuComponent.dispatchEvent(Unknown Source)
at java.awt.EventQueue.dispatchEvent(Unknown Source)
at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
at java.awt.EventDispatchThread.run(Unknown Source)

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1