Is there any way to accept only numeric values in a JTextField
? Is there any special method for this?
A simple approach is to subclass JTextField and override createDefaultModel() by returning customised PlainDocument subclass. Example - a textfield for integers only:
public class NumberField extends JTextField {
@Override
protected Document createDefaultModel() {
return new Numberdocument();
}
class Numberdocument extends PlainDocument
{
String numbers="1234567890-";
@Override
public void insertString(int offs, String str, AttributeSet a)
throws BadLocationException {
if(!numbers.contains(str));
else super.insertString(offs, str, a);
}
}
Process input in insertString() any way.