Is there any way to accept only numeric values in a JTextField
? Is there any special method for this?
A quick solution:
JTextField textField = new JTextField() {
public void processKeyEvent(KeyEvent ev) {
char c = ev.getKeyChar();
if (c >= 48 && c <= 57) { // c = '0' ... c = '9'
super.processKeyEvent(ev);
}
}
};
The problem with the above solution is that the user cannot use the Delete, Left Arrow, Right Arrow, or Backspace keys in the text field, so I suggest using this solution:
this.portTextField = new JTextField() {
public void processKeyEvent(KeyEvent ev) {
char c = ev.getKeyChar();
try {
// Ignore all non-printable characters. Just check the printable ones.
if (c > 31 && c < 127) {
Integer.parseInt(c + "");
}
super.processKeyEvent(ev);
}
catch (NumberFormatException nfe) {
// Do nothing. Character inputted is not a number, so ignore it.
}
}
};