【问题标题】:how to replace a word with in contains() Method form a JtextPane如何用 contains() 方法替换一个单词,形成一个 JtextPane
【发布时间】:2015-05-01 18:58:49
【问题描述】:

嗯,我正在尝试使用 contains() 方法替换一个单词:

String z = tfB.getText().toString();
String show = textPane.getText().toString();
   if(show.contains(z)){

     // how I specify the word that were found and change it without 
        effecting anything with in that line

   }

我的主要内容是:

我想做的是从用户那里获得价值。 然后搜索是否找到将其替换为某些内容。例如:

 String x = "one two three four five";

它应该将 textPane 设置为"one two 3 four five"

"one two 3-three-3 four five"

谁能告诉我怎么做。

谢谢

【问题讨论】:

  • 你在尝试替换之前不需要检查它是否存在。
  • 包含不替换。 contains 仅告诉您某些文本是否包含字符串。通过阅读 String 的 javadoc,您应该能够找到对替换有用的方法。文档是程序员最好的朋友。阅读。它是为你写的。

标签: java swing user-interface replace contains


【解决方案1】:

我想做的是从用户那里获得价值。然后搜索是否找到将其替换为某些内容。

不要使用contains() 方法,因为您需要搜索文本两次:

  1. 一次查看是否在字符串中找到文本
  2. 再次用新字符串替换文本。

改为使用String.indexof(...) 方法。如果在字符串中找到它,它将返回文本的索引。

那么您应该直接在文本窗格的 Document 中替换文本,而不是在 String 本身中。所以代码会是这样的:

int length = textPane.getDocument().getLength();
String text = textPane.getDocument().getText(0, length);
String search = "abc...";
int offset = text.indexOf(search);

if (offset != -1)
{
    textPane.setSelectionStart(offset);
    textPane.setSelectionEnd(offset + search.length();
    textPane.replaceSelection("123...");
}

另外,不是您从文档中获取文本,而不是从文本窗格中获取文本。这是为了确保在您替换文档中的文本时偏移是正确的。查看Text and New Lines,了解更多关于为什么这很重要的信息。

【讨论】:

  • @dragon3002,不客气,别忘了“接受”答案,这样人们就知道问题已经解决了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-15
  • 2015-09-11
  • 2015-03-02
  • 1970-01-01
相关资源
最近更新 更多