Jay Jay - 1 month ago 16
Java Question

Replacing a word with another word select by a user

I am trying to replace a word one occurrence at a time. I have been looking through other answers here, but I think what I have coded so far would be much simpler. I want to replace a word that a user selects with another word that the user also selects. I will have two text fields and a button and every time the user clicks the button, we will get the text out of both text fields and replace the word that needs to be replaced in the text area. My issue is that when the replace button is clicked, any other text that is in the text area is deleted and we are left only with the word that is doing the replacing. I know my issue is because I am setting the text of the text area to just that one word, but I do not know how to fix it. Here is my code: Any help is appreciated.

replaceButton.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String findText = textField.getText();
String replaceText = textField2.getText();
String text = textArea.getText();

text += text.replaceFirst(findText, replaceText);
textArea.setText(replaceText);

}
});

Answer

Like you said. You are setting the text in textArea to the text you want to replace. So set the text in textArea to the updated text returned from text.replaceFirst(findText, replaceText). Also you don't need to concatenate the result.

Try this.

replaceButton.addActionListener( new ActionListener()
{
    public void actionPerformed(ActionEvent e)
    {
        //the text you want to replace
        String findText = textField.getText();
        //what you want to replace it with
        String replaceText = textField2.getText();
        //all the text in the text area
        String text = textArea.getText();

        //replace first occurrence of "findText" with "replaceText"
        //returns the altered string
        text = text.replaceFirst(findText, replaceText);
        //set text in textArea to newly updated text
        textArea.setText(text);

    }
});

To make sure I understand you correctly you want something like this.

Original text: I like cats, cats are cool.

find: cats; replace: dogs.

First click output: I like dogs, cats are cool.

Second click output: I like dogs, dogs are cool.