Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement in Java ( JTextField class ) to allow entering only digits?

How to implement in Java ( JTextField class ) to allow entering only digits?

like image 519
Damir Avatar asked Apr 14 '11 11:04

Damir


People also ask

How do you accept only numbers in Java?

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.

How do I limit text in JTextField?

We can restrict the number of characters that the user can enter into a JTextField can be achieved by using a PlainDocument class.

How do I allow only numbers in a textbox in Java?

You can add KeyListener to prevent the user from entering non-numeric characters in a JTextField.

Which method of a JTextField allows you to retrieved the values inputted by the user?

Notice the use of JTextField 's getText method to retrieve the text currently contained by the text field.


2 Answers

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);
like image 147
user85421 Avatar answered Sep 20 '22 14:09

user85421


Use a JFormattedTextField.

http://download.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

like image 42
jzd Avatar answered Sep 17 '22 14:09

jzd