How to implement in Java ( JTextField class ) to allow entering only digits?
How to implement in Java ( JTextField
class ) to allow entering only digits?
Solution 1:
Add a DocumentFilter to the (Plain)Document used in the JTextField to avoid non-digits.
PlainDocument doc = new PlainDocument();
doc.setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int off, String str, AttributeSet attr)
throws BadLocationException
{
fb.insertString(off, str.replaceAll("\\D++", ""), attr); // remove non-digits
}
@Override
public void replace(FilterBypass fb, int off, int len, String str, AttributeSet attr)
throws BadLocationException
{
fb.replace(off, len, str.replaceAll("\\D++", ""), attr); // remove non-digits
}
});
JTextField field = new JTextField();
field.setDocument(doc);
Solution 2:
Use a JFormattedTextField
.
http://download.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html
Solution 3:
Use a Document
implementation whose insertString
method filters out the non-digit characters.
Solution 4:
Use this class, and call it where you need to validation pass your jtexField name as parameter.
exm:- setNumericOnly(txtMSISDN); here txtMSISDN is my jtextField.
public static void setNumericOnly(JTextField jTextField){
jTextField.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if ((!Character.isDigit(c) ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE))) {
e.consume();
}
}
});
}