Creating a Simple Text Editor in Java

er.. I don't even know what I am doing..

Page 1 of 1

0 Replies - 2545 Views - Last Post: 01 March 2010 - 04:28 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

Creating a Simple Text Editor in Java

Posted 01 March 2010 - 04:28 PM

Hiya guys, My first time posting in the Java Section. Anyways, quick backstory: I finished C and decided to take the Java Course. I am very confused about how to this project... and by confused I mean: I have no clue what I'm doing. So, attempting to explain my problem as best as I can.

We were given starter code to help create a simple Text Editor. So I'm working on the first and supposedly easiest part: Opening a file. But really, I don't even know what to do. So here's what I've got
the EditorMenuHandler Class
/* 
 * 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 {
	   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 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());
		SimpleFileReader read= SimpleFileReader.openFileForReading(filedialog.getFile()+
				filedialog.getDirectory());
		filedialog = new FileDialog(editor, read, FileDialog.LOAD);
	    
	    }
	}
	//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());
	    }
	}
	//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.
    }
}


All this is supposed to do is just let me save/open files, and mess with files.
Right now, the part I'm stuck on is:
	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());
		SimpleFileReader read= SimpleFileReader.openFileForReading(filedialog.getFile()+
				filedialog.getDirectory());
		filedialog = new FileDialog(editor, read, FileDialog.LOAD);
	    
	    }
	}


Really, I don't even know what to do. I would use FileOutputStream and the Jpanel commands, except I have to use the starter code provided.
I also have a simple file reader, but I'm not really sure about getting the all the stuff from the document to the text area.... Actually, let's just be honest about this: I can't even make it print in the console. So, any help there would also be appreciated.
SimpleFileReader Class -- Have to use this to make the stuff print... :/
/* 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;

}


Please, help me help you help me. I don't really even know what to ask right now, other than for hints on making the file open.

Oh, and the "Marking Scheme"
Marking Scheme for Project_01
Coding:
Files submitted correctly & compiles correctly..........................[/10]
Neglibible modifications to my code.....................................[/2]
(E.g SearchDialog.java should be unchanged)
Methods for MenuHandler to request services from Editor.................[/12]
(open, save, search, cut, copy, paste)
E.g. MenuHandler *must not* directly access Editor's TextArea!
Cut 'n paste buffer private.............................................[/2]
Bonus for StringBuffer loading..........................................[/2]
VERBOSE flag turned off.................................................[/2]

Subtotal................................................................[/30]

Functionality:
Load and save robust (checks that dir & file selected not null).........[/2]
Loads files correctly, caret at top.....................................[/2]
Bonus for "no scrolling on loading".....................................[/2]
Saves files correctly (diff detects no difference)......................[/2]
Search works correctly..................................................[/2]
Cut works correctly.....................................................[/2]
Copy works correctly....................................................[/2]
Paste works correctly...................................................[/2]
Bonus version with bells and whistles...................................[/4]

Subtotal................................................................[/20]

Total...................................................................[/50]

Byt the way, the "Bonuses" have to be done. :/

This'll be a process, but I'm trying to get about 2 a week, (don't have very long to do it). Any help would be appreciated.

-----------------------
So apparently I can't upload the other files, which will make this quit lengthy. SORRY!
/*
 * 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
     */
    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>
    }
}


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


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

}


Sorry for the length... if It's messy/unclear/anything feel free to PM me as well as reply. I really need help with this one.

Oh and I use eclipse since it's what was suggested. I don't think it makes a difference in Java, but just to be clear.

This post has been edited by hawkysu: 01 March 2010 - 04:31 PM


Is This A Good Question/Topic? 0
  • +

Page 1 of 1