0

I have assigment to make notepad using NetBeans Java. I already made the whole thing, I just don't know how to implement find/replace dialog, can you help me with this. I'm using jTextArea.

Alen
  • 1,750
  • 7
  • 31
  • 62

2 Answers2

1

I will assume that you already know about Swing and how to make the appropriate dialog box (since you apparently have already made the JTextArea for the Notepad equivalent), and that you just want to know how to make it work on the back end.

What I would do is have a Scanner object go through your file to perform the find and replace.

String myAlteredText = "";
Scanner scanner = new Scanner(myText);

while(scanner.hasNext()) {
    String next = scanner.next();
    if(next.equals(userFindInput)) {
        myAlteredText += userReplaceInput;
    }
    else {
        myAlteredText += next;
    }
    myAlteredText += " ";
}

You can use .equalsIgnoreCase() if case doesn't matter. Likewise, you can tweak to adjust to your user parameters (i.e., if it doesn't have to match the whole word, use .contains() instead). There may be some nit-picky other things you need to do to maintain abnormal spacing and line breaks, but this is the general approach I would use.

asteri
  • 11,402
  • 13
  • 60
  • 84
  • what's "myText", is that text from textArea? and how to highlight the word(s) I found in textArea. – Alen Dec 29 '12 at 17:09
  • Yes, I'm assuming `myText` is the text in your Notepad-equivalent. For highlighting techniques, see [this question](http://stackoverflow.com/questions/5674128/jtextpane-highlight-text). – asteri Dec 29 '12 at 17:11
0

You could use a JTable although this is rather unconventional. You could load each word into a new cell. This way when you need to replace 1 word you don't need to update the entire jtextarea for just 1 character unless I am mistaken. This would require a lot of work however in order to get this to work

Aaron
  • 101
  • 1