我无法使用JButton从textField中删除不需要的字符。 到目前为止,我已尝试使用for循环按钮调用遍历字符并将所有字母字母实例替换为0.但是按钮实际上并没有做任何事情。任何帮助将不胜感激,这是我的代码:
if(event.getSource() == call)
{
int length = search.getText().length();
for(int i = 0; i < length; i++)
{
char a;
a = search.getText().charAt(i);
if(!(a >= '0' && a <= '9') || !(a == '#') || !(a == '*')
{
search.getText().replace(Character.toString(a), "");
}
}
}
search是我的textField的名字,在通话中我想删除任何不在0-9或#或*键之间的字符。
答案 0 :(得分:3)
这一行search.getText().replace(Character.toString(a), "");
应该是这样的
search.setText(search.getText().replace(Character.toString(a), ""));
而不是为每次迭代更改和更新一个字符,你可以这样做。
String searchStr= search.getText();
for(int i = 0; i < searchStr.length(); i++)
{
char a;
a = searchStr.charAt(i);
if(!(a >= '0' && a <= '9') || !(a == '#') || !(a == '*')
{
searchStr = searchStr.replace(Character.toString(a), "");
}
}
search.setText(searchStr);
答案 1 :(得分:1)
使用replace
方法时,它将返回String。
/**
* Replaces each substring of this string that matches the literal target
* sequence with the specified literal replacement sequence. The
* replacement proceeds from the beginning of the string to the end, for
* example, replacing "aa" with "b" in the string "aaa" will result in
* "ba" rather than "ab".
*
* @param target The sequence of char values to be replaced
* @param replacement The replacement sequence of char values
* @return The resulting string
* @throws NullPointerException if <code>target</code> or
* <code>replacement</code> is <code>null</code>.
* @since 1.5
*/
public String replace(CharSequence target, CharSequence replacement) {
return Pattern.compile(target.toString(), Pattern.LITERAL).matcher(
this).replaceAll(Matcher.quoteReplacement(replacement.toString()));
}
因此,当您使用替换时,您应该像以下方式一样使用它:
` searchStr = searchStr.replace(Character.toString(a), ""); `
而不是searchStr.replace(Character.toString(a), "");
以便可以替换该值。
如果您之前使用的代码searchStr.replace(Character.toString(a), "");
字符串值searchStr,则不会更改。
另外,您也可以使用正则表达式删除意外的字符。 等,
if(event.getSource() == call)
{
//remove any character that is not between 0-9 or the # or * keys.
String text = search.getText();
text = text.replaceAll("[^0-9#*]", "");
//Set new text to search
search.setText(text);
}