2016-10-11 99 views
1

我正在使用文本编辑器,我希望用户能够找到并替换他们选择的单词。我目前有代码来替换这个词,但它一次代替了这个词的所有出现。我实际上想在这个时候替换一次。例如,如果用户想用“狗”代替“猫”,他们将不得不点击一个按钮,它将代替它找到的第一个“猫”,然后用户将不得不再次单击该按钮来替换其他一次一个。我在这里查看了一些问题,但其中大部分似乎都是一次性替换所有事件,这就是我所遇到的问题。这是我迄今为止所拥有的。在此先感谢任何能够帮助我的人。如何在java中一次查找并替换一个单词?

class Bottom extends JPanel 
{ 
    private JPanel bottomPanel = new JPanel(); 
    private JButton replaceButton = new JButton("Replace"); 
    private JTextField textField = new JTextField("", 15);; 
    private JLabel label = new JLabel(" with "); 
    private JTextField textField2 = new JTextField("", 15); 

    public Bottom() 
    { 
    bottomPanel.add(replaceButton); 
    bottomPanel.add(textField); 
    bottomPanel.add(label); 
    bottomPanel.add(textField2); 
    add(bottomPanel); 

    replaceButton.addActionListener(new ActionListener() 
    { 
     public void actionPerformed(ActionEvent e) 
     { 
      try{ 
      String findText = textField.getText(); 
      int findTextLength = findText.length(); 
      String replaceText = textField2.getText(); 
      int replaceTextLength = replaceText.length(); 
      Document doc = textArea.getDocument(); 
      String text = doc.getText(0, doc.getLength()); 
      int counter = 0; 
      int lengthOffset = 0; 

      while ((lengthOffset = text.indexOf(findText, lengthOffset)) != -1) 
      { 
       int replaceOffset = lengthOffset + ((replaceTextLength - findTextLength) * counter); 
       textArea.select(replaceOffset, replaceOffset + findTextLength); 
       textArea.replaceSelection(replaceText); 

       lengthOffset += replaceTextLength; 

       counter++; 
      } 
      }catch(BadLocationException b){b.printStackTrace();} 
     } 
    }); 
} 

}

回答

1

替换whileif

你的循环说“只要你发现更多的事件,不断更换”。如果您希望它仅替换第一个匹配项,那么它可能应该是“如果您发现某个事件,请替换”。

另一种解决方案可能是将您的“替换”按钮重命名为“全部替换”;-)

+0

当然,它会是如此简单。我甚至没有想到这一点。非常感谢。这绝对解决了整个问题,而无需使用replaceFirst方法。谢谢! – Jay

相关问题