【问题标题】:Replacing a word with another word select by a user用用户选择的另一个词替换一个词
【发布时间】:2016-10-26 18:53:01
【问题描述】:

我试图一次替换一个单词。我一直在这里查看其他答案,但我认为到目前为止我编写的代码会简单得多。我想用用户也选择的另一个词替换用户选择的词。我将有两个文本字段和一个按钮,每次用户单击按钮时,我们都会从两个文本字段中获取文本并替换文本区域中需要替换的单词。我的问题是,当单击替换按钮时,文本区域中的任何其他文本都将被删除,我们只剩下正在替换的单词。我知道我的问题是因为我将文本区域的文本设置为一个单词,但我不知道如何解决它。这是我的代码:感谢任何帮助。

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

        }
    });

【问题讨论】:

    标签: java replace jtextarea


    【解决方案1】:

    就像你说的。您正在将 textArea 中的文本设置为要替换的文本。所以将textArea中的文本设置为text.replaceFirst(findText, replaceText)返回的更新文本。您也不需要连接结果。

    试试这个。

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

    为了确保我正确理解你,你想要这样的东西。

    原文:我喜欢猫,猫很酷。

    找到:猫;替换:狗。

    首次点击输出:我喜欢狗,猫很酷。

    二次点击输出:我喜欢狗,狗很酷。

    【讨论】:

    • 没错。该解决方案奏效了。我只是处于那种需要将文本区域中的文本设置为 replaceText 字段的心态。非常感谢!
    猜你喜欢
    • 2012-02-26
    • 2019-09-24
    • 1970-01-01
    • 2015-03-02
    • 1970-01-01
    • 2021-07-22
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    相关资源
    最近更新 更多