How to implement in Java ( JTextField
class ) to allow entering only digits?
To only accept numbers, you can do something similar using the Character. isDigit(char) function, but note that you will have to read the input as a String not a double , or get the input as a double and the converting it to String using Double. toString(d) . Save this answer.
We can restrict the number of characters that the user can enter into a JTextField can be achieved by using a PlainDocument class.
You can add KeyListener to prevent the user from entering non-numeric characters in a JTextField.
Notice the use of JTextField 's getText method to retrieve the text currently contained by the text field.
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);
Use a JFormattedTextField
.
http://download.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With