import java.io.*; import java.awt.*; import javax.swing.*; import java.awt.event.*; public class FindAndRepl extends JFrame { protected JTextArea text; /* Constructor */ public FindAndRepl() { setTitle("My First GUI App"); setSize(500, 300); // width and height setLocation(50, 50); text = new JTextArea("Some text ... "); text.setLineWrap(true); // wrap long lines text.setWrapStyleWord(true); // wrap at spaces /* But since text is long */ getContentPane().add(new JScrollPane(text)); /* The magic window terminator */ addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent evt) { System.exit(0); } }); } /* * Reads the specified file and adds the text to the * text area */ public void readFile(String file) { BufferedReader bf; String line = ""; try { bf = new BufferedReader(new FileReader( new File(file))); text.setText(""); // empties the text area /* Reads and tests at the same line */ while ((line = bf.readLine()) != null) { text.append(line + "\n"); // line and line feed } } catch (Exception e) {} // Any error is ignored } /* * Get the document and finds the occurences of the * the specified String. Second argument is the optional * replace string. This method calls a helper method. */ public void findString(String find, String replace) { String doc = text.getText(); doc = helpFind(doc, find, replace); text.setText(doc); } /* * A helper method (hence private) that will do the * recursion. It is called from findStrin. If no replacement * argument is given, that is 'replace' is null, this method * will replace the found string with itself uppercased. */ private String helpFind(String txt, String fnd, String rpl) { int fIndex = txt.indexOf(fnd); if (fIndex < 0) { // no more occurences of 'fnd' return txt; } else { // index shows the first occurence of 'fnd' /* adds the first part of the text, up to the string * searched for */ StringBuffer buff = new StringBuffer(txt.substring(0, fIndex)); if (rpl.equals("")) { // no replacement argument buff.append(fnd.toUpperCase()); } else { buff.append(rpl); } /* Here comes the recursive call, with the remainder * of the given string 'txt'. Now 'buff' will hold * the "middle value" of the text, that is from the * former index+length_of_fnd and up to the index of * this turn in 'helpFind()', and appended will be * the value returned from the recursive call. */ /* Note that it is possible to break statements * almost at any place of your choice, Java is very * forgiving. It is still one statement, ending * with a semicolon. Note the matching pairs of * parentheses as well. */ buff.append( helpFind(txt.substring(fIndex + fnd.length()), fnd, rpl) ); /* Now buff holds the same middle value and the * remainder of the text appended to it. */ return buff.toString(); } } }