Text Editor - Search

Only two more parts left

Page 1 of 1

4 Replies - 2158 Views - Last Post: 18 March 2010 - 09:18 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 - Search

Posted 17 March 2010 - 03:36 PM

Hey Guys,
Moving on with the text editor program, I decided to start working on the search function (since I was sick of failing at save :/ ) and... welllll... It ain't very pretty, and it ain't workin'.
Anyways, all it needs to do is highlight a word that the user types into the little box after hitting search. My main problem is getting hilit to work, as it gives me an error when I don't give it any value, and it crashes when I set it to null :/
Anyways, heres teh codez:
editor.java
/*
 * 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>
    }
    
    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();
    	
    }
    
    public void Save(String name){
    	SimpleFileWriter write= SimpleFileWriter.openFileForWriting(name);
    	if(write==null) return;
    	while(textArea.getText()!=null){
    		write.print(textArea.getText());
    	}
    	write.close();
    }
    
	public void Search(SearchDialog searcher){
		String theText= searcher.getText();
		final Color  HILIT_COLOR = Color.LIGHT_GRAY;
		final Color  ERROR_COLOR = Color.PINK;
		final Color entryBg = Color.YELLOW;
		final Highlighter hilit;
		final Highlighter.HighlightPainter painter = null;
		
		//System.out.println(theText);
		
        hilit.removeAllHighlights();
        if (theText.length() <= 0) {
            System.err.println("Nothing to search");
            return;
        }
        
        String content = textArea.getText();
        int index = content.indexOf(theText, 0);
        System.out.println("test1");
        if (index >= 0) {   // match found
            try {
                int end = index + theText.length();
                hilit.addHighlight(index, end, painter);
                System.out.println("test2");
                textArea.setCaretPosition(end);
                searcher.setBackground(entryBg);
                System.err.println("'" + theText + "' found. Press ESC to end search");
            } catch (BadLocationException e) {
                e.printStackTrace();
            }
        } else {
            textArea.setBackground(ERROR_COLOR);
            System.err.println("'" + theText + "' not found. Press ESC to start a new search");
        }
    }
    
    /**
     * 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());
    }
}


This is the one that does everything

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


This is the one that tells editor what to do.

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



This makes a purdy lil' search box

-------------------------------
And then, in case ya feel you need to run it, here are the other files.

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;

}


SimpleFileReader.java
/* 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;

}


CenteredFrame.java
/* comp285 CenteredFrame.java
 */
import java.awt.*;

/**
 * CenteredFrame is a simple subclass of Frame that uses the
 * Toolkit to center the frame in the middle of the screen, 
 * and sizes it to be half the height and width of the screen.
 * @see          java.awt.Toolkit
 * @see          java.awt.Frame
 * @version      1.0 beta 
 * @author       Ian A Mason
 */

public class CenteredFrame extends Frame{
    /**
     * The CenteredFrame contructor, contructs an initially 
     * invisible frame, it uses the Toolkit to center the 
     * frame in the middle of the screen, and size
     * it to be half the height and width of the screen.
     */
     public CenteredFrame(String title){
	 super(title);
	 Dimension d = 
	     Toolkit.getDefaultToolkit().getScreenSize();
	 int screenH = d.height;
	 int screenW = d.width;
	 setSize(screenW/2, screenH/2);
	 setLocation(screenW/4, screenH/4);
     }

    /**
     *  For testing, constructs a CenteredFrame object 
     *  and then makes it visible.
     */
     public static void main(String[] args) {
	 CenteredFrame f = new CenteredFrame("Centered Frame");
	 f.setVisible(true);
     }
     
     
 }



Anyways, I'd be more specific about my problem, but from what I've read/tried, I don't even know why this'd be happening.
Plazhalp! ;)
thanks in advanced. (guilt you into helping me :D)

This post has been edited by hawkysu: 17 March 2010 - 03:36 PM


Is This A Good Question/Topic? 0
  • +

Replies To: Text Editor - Search

#2 macosxnerd101  Icon User is offline

  • Self-Trained Economist
  • member icon




Reputation: 10767
  • View blog
  • Posts: 40,091
  • Joined: 27-December 08

Re: Text Editor - Search

Posted 17 March 2010 - 04:59 PM

Can you post the error message(s) you are encountering? Also, you can check the length of the String you entered before searching. So if(stringInput.trim().length() == 0).
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 - Search

Posted 18 March 2010 - 07:59 PM

yea, the error messages are:

hilit.addHighlight(index, end, painter);
hilit.removeAllHighlights();


The local variable hilit may not have been initialized Editor.java /Editor/src line 189 (201) Java Problem

for when I don't initialize it, and the searchdialog box doesn't even show up when I do.

Also, about finding the size of the string before I search, do you mean in the EditorMenuHandler class?, just before I call editor.Search(w/e)?
	//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");
	    
	    if(searchDialog.getText().length()!=0){
	    editor.Search(searchDialog);
	    }
	}



EDIT:
Also,
 final Highlighter hilit= new Highlighter();
doesn't seem to work :/

This post has been edited by hawkysu: 18 March 2010 - 08:03 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 - Search

Posted 18 March 2010 - 08:34 PM

Ahaha, no need for fancy junk:

	public void Search(SearchDialog searcher){
		String theText= searcher.getText();
        if (theText.length() <= 0) {
            System.err.println("Nothing to search");
            return;
        }
        
        String content = textArea.getText();
        int index = content.indexOf(theText, 0);
        if (index >= 0) {   // match found
                int end = index + theText.length();
                textArea.select(index,end);
                searcher.setBackground(Color.YELLOW);
            }
        else {
            searcher.setBackground(Color.RED);
            System.err.println("'" + theText + "' not found. Press ESC to start a new search");
        }
    }



However, when I have a lot of text, and then have it go through and find a word, sometimes it's a little bit off. Can anyone help me fix that?

EDIT:
Actually, it's only off by one for every newline.

This post has been edited by hawkysu: 18 March 2010 - 08:50 PM

Was This Post Helpful? 0
  • +
  • -

#5 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 - Search

Posted 18 March 2010 - 09:18 PM

HAHA! I r teh 1337.

It isn't pretty, but at least it highlights what it is supposed to now.
:D
	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.");
        }
    }


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1