Reputation: 5308
I need to restrict the user for entering Numbers (0-9) in an EditText and allow every other character from the keyboard.
The following code is not working on the following scenario.
If the user enters an alphabet and then a number, the editText becomes empty.
InputFilter withoutNumberFilter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (Character.isDigit(source.charAt(i))) {
return "";
}
}
return null;
}
};
editText.setFilters(new InputFilter[] { withoutNumberFilter });
Upvotes: 2
Views: 56
Reputation: 3
Extending you class might help and implement a listener. You then can re-use your extended JTextField in other Forms.
Just a simple example.
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import javax.swing.JTextField;
public class MyJTextField extends JTextField implements KeyListener {
public MyJTextField() {
super();
addKeyListener(this);
}
boolean found = false;
@Override
public void keyPressed(KeyEvent arg0) {
char c = arg0.getKeyChar();
char[] cs = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
for (int i = 0; i < cs.length; i++) {
if (c == cs[i]) {
found = true;
break;
}
}
}
@Override
public void keyReleased(KeyEvent arg0) {
if (found) {
String text = getText();
setText(text.substring(0, text.length() - 1));
found = false;
}
}
@Override
public void keyTyped(KeyEvent arg0) {
// No action.
}
}
Any other comments are welcome.
Upvotes: 0
Reputation: 185
You can use the isLetter()
method to compare
if (!Character.isLetter(source.charAt(i))) {
return "";
}
Upvotes: 1
Reputation: 171
You just need to update your condition to:
if (!Character.isLetter(source.charAt(i)))
That should do the trick.
Upvotes: 1
Reputation: 2799
Just use a regex to replace all digits:
source = source.replaceAll("[0-9]","")
If you want to do it as the user is entering input, then just input this statement after every action event.
Upvotes: 0