I used to use the Key Listener for this but I failed big time with that approach. Best approach as recommended already is to use a DocumentFilter. Below is a utility method I created for building textfields with only number input. Just beware that it'll also take single '.' character as well since it's usable for decimal input.
public static void installNumberCharacters(AbstractDocument document) {
document.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset,
String string, AttributeSet attr)
throws BadLocationException {
try {
if (string.equals(".")
&& !fb.getDocument()
.getText(0, fb.getDocument().getLength())
.contains(".")) {
super.insertString(fb, offset, string, attr);
return;
}
Double.parseDouble(string);
super.insertString(fb, offset, string, attr);
} catch (Exception e) {
Toolkit.getDefaultToolkit().beep();
}
}
@Override
public void replace(FilterBypass fb, int offset, int length,
String text, AttributeSet attrs)
throws BadLocationException {
try {
if (text.equals(".")
&& !fb.getDocument()
.getText(0, fb.getDocument().getLength())
.contains(".")) {
super.insertString(fb, offset, text, attrs);
return;
}
Double.parseDouble(text);
super.replace(fb, offset, length, text, attrs);
} catch (Exception e) {
Toolkit.getDefaultToolkit().beep();
}
}
});
}