Please assist with text editor

Hi Everylone, I'm new in java and have a project to fix that is a not working text editor, particulary, Save, Open, Copy, Paste, and Search. I did some work, however i didn't get to the final result, those functions listed above don't work.

Please can someone help with ideas. Thank you in advance

package test;

/* comp285 CenteredFrame.java

*/

import java.awt.*;

import java.awt.Toolkit.*;

import java.awt.Event.*;

import java.awt.Frame.*;

import java.io.*;

/**

* 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

* @version1.0 beta

* @authorIan A Mason

*/

publicclass CenteredFrameextends 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.

*/

publicstaticvoid main(String[] args)

{

CenteredFrame f =new CenteredFrame("Centered Frame");

f.setVisible(true);

}

}

__

package test;

/*

* comp285 SearchDialog Widget

*/

import java.awt.*;

import java.awt.event.*;

/**

* This here widget is used by the EditMenuHandler, come back now, ya hear!

* @authorIan A Mason.

* @version 1.0 beta

* @date 8/03/01

* @see java.awt.Dialog

*/

publicclass SearchDialogextends Dialog{

/**

*

* @see java.awt.TextField

*/

final TextField target =new TextField(12);

/**

*

* @see java.awt.Button

*/

Button button =new Button("Search File");

/**

*

*

*/

Button closeButton =new Button("Close");

protected String getText(){return target.getText();}

/**

*

*/

public SearchDialog(Editor editor){

super(editor,"Search Dialog",true);

final Editor Editor = editor;

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(){

publicvoid 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());

}

});

closeButton.addActionListener(new ActionListener(){

publicvoid actionPerformed(ActionEvent ae){

if(Editor.VERBOSE)

System.out.println("Shutting down dialog " +

"(terminating call to dialog.show();");

SearchDialog.this.dispose();

if(Editor.VERBOSE)

System.out.println("String to be searched for = " +

target.getText());

}

});

}

}

package test;

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

*

*

* @seejava.io.FileReader

* @see java.io.BufferedReader

* @version1.1 10/01/99

* @authorJulie Zelenski

*/

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

*/

publicstatic SimpleFileReader openFileForReading(String filename)

{

try{

returnnew SimpleFileReader(new BufferedReader(new FileReader(filename)));

}catch(IOException e){

returnnull;

}

}

/**

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

returnnull;

}

}

/**

* Closes the file when done reading. You should close a reader when

* you are finished to release the OS resources for use by others.

*/

publicvoid 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;

}

package test;

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

* @version1.1 10/01/99

* @authorJulie Zelenski

*/

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

*/

publicstatic SimpleFileWriter openFileForWriting(String filename)

{

try{

returnnew SimpleFileWriter(new PrintWriter(new FileWriter(filename),true));

}catch(IOException e){

returnnull;

}

}

/**

* Appends a string to the end of the file without adding any

* trailing new line.

*/

publicvoid print(String s)

{

writer.print(s);

}

/**

* Appends a string to the end of the file and adds a

* trailing new line.

*/

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

*/

publicvoid 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;

}

_

package test;

/*

* comp285 Editor class

*/

import java.awt.*;

import java.awt.event.*;

/**

*

* @authorIan A Mason.

* @see CenteredFrame

* @see java.awt.Frame

* @version 1.0 beta

* @date 7/02/01

*/

class Editorextends 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!

*/

protectedstaticfinalboolean VERBOSE =false;

/**

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

*/

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

*/

protectedstaticfinal 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

*/

privatefinal TextAreatextArea =new TextArea("", 40, 80, TextArea.SCROLLBARS_BOTH);

public TextArea getTextArea()

{

return textArea;

}

/**

* 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

*/

privatefinal MenuBarmenuBar =new MenuBar();

/**

* The file menu is the thing that one clicks on to pull down the menu items.

* @see java.awt.Menu

*/

privatefinal 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

*/

privatefinal 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

*/

privatefinal 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

*/

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

*/

privatevoid initMenu(MenuItem[] menuItems,

String[] menuLabels,

Menumenu,

EditorMenuHandler menuHandler,

MenuBarmenuBar){

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.

*/

publicstaticvoid 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>

}

}

_-

package test;

/*

* comp285 EditorMenuHandler class

*/

import java.awt.*;

import java.awt.event.*;

import java.io.*;

/**

* The EditorMenuHandler that handles the events generated by the

* menu of the Editor class.

* @authorIan A Mason.

* @version 1.0 beta

* @date 7/02/01

* @see java.awt.event.ActionListener

* @see java.awt.event.ItemListener

*/

class EditorMenuHandlerimplements 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;

String heading =" Save File ";

String fileName=null;

String s;

TextArea tx1=new TextArea();

privateboolean lentest(){

s=tx1.getText();

int len=s.length();

if(len>0)return (true);elsereturn(false);}

/**

* 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

*/

publicvoid actionPerformed(ActionEvent ae){

FileDialog filedialog;

final SearchDialog searchDialog;

String arg = (String)ae.getActionCommand();

//fileLabels[].addActionListener(this);

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

}

}

//the Save ... case

if(arg.equals(Editor.fileLabels[1]))

{

heading=" Save File ";saveOpenedFile();

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");

}

}

privateboolean write (String filename){

FileOutputStream os=null;

try{

os=new FileOutputStream(filename);

}catch(Throwable e){

return(false);

}

try{

String s=tx1.getText();

int len=s.length();

for(int i=0;i<len;i++){

os.write(s.charAt(i));

}

os.close();

}

catch(IOException e){

return(false);

}

return(true);

}

publicvoid saveOpenedFile()

{

if(!lentest()) ;else

if(fileName==null){

//showErrorDialog("You did not previously open a file.Use save as.");

}else{

write(fileName);

tx1.requestFocus();

}

}

/**

* This needs to be here since we need to implement the ItemListener

* interface

* @see java.awt.event.ItemListener

*/

publicvoid itemStateChanged(ItemEvent ie){

//shouldn't need to do anything here.

}

}

>

[34607 byte] By [AdiVa] at [2007-11-27 5:35:05]
# 1
You should post this in the Swing forum and explain in more detail what doesn't work means to the people there. Post any errors you are getting also.
_helloWorld_a at 2007-7-12 15:03:47 > top of Java-index,Java Essentials,New To Java...
# 2

Thank you for the advice, but unfortunately the project does not allow to use javax.swing but only java.awt.

That is why I am stuck in this situation and kindly ask for assistance.

When I run the proggram, I do not recieve any errors, but simply put when I use the operations they do not function.

i.e. save does not save; cut does not cut, etc.

Message was edited by:

AdiV

AdiVa at 2007-7-12 15:03:47 > top of Java-index,Java Essentials,New To Java...
# 3

i didn't get to the final result, those functions listed above don't work

Try to use what was given to complete the implementations.

The EditorMenuHandler class is the place to focus.

For example, implementing the open item:

public void actionPerformed(ActionEvent ) {

// the Open ... case

if(arg.equals(Editor.fileLabels[0])){

if(Editor.VERBOSE){

...

}

// Save the selected folder and file names.

String folderName = fileDialog.getDirectory();

String fileName = fileDialog.getFile();

// Avoid NullPointerExceptions.

if(fileName != null)

readFile(folderName + fileName);

}

...

}

private void readFile(String path) {

// The Editor class has the textArea that is shown in the

// gui and provides a method to get a reference to it.

TextArea textArea = editor.getTextArea();

// See comments in SimpleFileReader class for the

// example code that shows how to use the class.

// Adapt it to your needs, like this:

SimpleFileReader reader = SimpleFileReader.openFileForReading(path);

if (reader == null) {

System.out.println("Couldn't open file!");

return;

}

String line;

while ((line = reader.readLine()) != null)

textArea.append(line + "\n");

reader.close();

}

crwooda at 2007-7-12 15:03:47 > top of Java-index,Java Essentials,New To Java...
# 4

I see, so for the save case I will do something similiar using the SimpleFileWriter.

And thanks for the code example, although when I try it I keep getting an eror messege saying that void is an invalid type for readFile any idea on how to fix this?

I aslo did some work on the copy/paste/cut, but there must be something wrong with them since they do not work. Here is what I added:

//This is in EditorMenuHandler

public void copy(){

copystring=editor.getSelectedText();

editor.requestFocus();

}

public void paste(){

if(copystring.length()>0)

editor.insert(copystring,editor.getSelectionStart());

editor.requestFocus();

}

public void cut(){

copystring = editor.getSelectedText();

editor.replaceRange("",editor.getSelectionStart(),editor.getSelectionEnd());

editor.requestFocus();

}

//*****************************************************

//This is in Editor

String tx;

String selectedtx;

int select;

int selectend;

int position;

//For Copy

public String getText(){

return tx;

}

//For Cut

public String getSelectedText(){

return selectedtx;

}

public int getSelectionStart(){

return select;

}

public int getSelectionEnd(){

return selectend;

}

public void replaceRange(String text, int start, int end){

text = selectedtx;

start = select;

end = selectend;

}

//For Paste

public void insert(String text, int pos){

text = selectedtx;

pos = position;

}

AdiVa at 2007-7-12 15:03:47 > top of Java-index,Java Essentials,New To Java...
# 5

keep getting an eror messege saying that void is an invalid type for readFile any idea

on how to fix this?

As a guess: are you returning anything from the method? A method with a void return type

(in its method signature) can have return statements but must not return anything, eg,

"return null" or "return aVariable". Or it could mean that the statement that calls the

method is expecting something returned, eg, "int pos = readFile(args)". Need more

information if these guesses came up dry.

When you get errors in the console they usually give a line number and error type, eg,

NullPointerException. These can both be helpful in tracing problems to their source.

Posting code works, too.

did some work on the copy/paste/cut

I would avoid adding things to the Editor class since it is mainly concerned with creating

and assembling components. You can make up helper methods in the EditorMenuHandler class

if/as needed.

The basic idea for the copy case is to get a reference to the textArea in editor, get the

selected text in it, get a reference to the system clipboard (hint: textArea.getToolkit)

and set the text to the clipboard (try wrapping it in a StringSelection).

For paste: get a reference to the clipboard, get its contents (Transferable) and get the

String data from the transferable (see api). Find the caret position in the textArea and

insert the text at that position.

The cut work is like the copy part as far as getting the text copied to clipboard. The

removal of it from the textArea is a little more involved. Since we appended text in the

textArea with newLines (in the readFile method) the text positions will be off by the

number of newLines above the line we are selecting text on. So you'll have to reduce the

start and end textSelection positions by these extra newLines to get accurate positions

for the removeRange method arguments. Of course there are other ways of doing this

part.

crwooda at 2007-7-12 15:03:47 > top of Java-index,Java Essentials,New To Java...