12

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

jzd
  • 23,473
  • 9
  • 54
  • 76
Damir
  • 54,277
  • 94
  • 246
  • 365

5 Answers5

17

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);
user85421
  • 28,957
  • 10
  • 64
  • 87
  • And what does AttributeSet mean? Because when I try to run this code java is giving error message. – Bakhtiyor Feb 28 '12 at 05:49
  • @Bakhtiyor - The AttributeSet is the collection of attributes (color, font, ...) of the given text. Why not write which error message? I suppose you have to `import javax.print.attribute.AttributeSet;`. – user85421 Feb 28 '12 at 11:25
  • Hi @CarlosHeuberger. If I want the user to enter only bytes in the JTrextField, then what should I do? For example, I am right now using simply the following: - `t3 = new JTextField("256"); t3.setBounds(100,150,150,20);` _"256" is just for showing the user the default value in the UI._ Thanks & Regards. – Vibhav Chaddha Jan 09 '17 at 06:09
  • sorry @VibhavChaddha not sure what you understand as "only byte", but you can probably use the same concept as above: add a `DocumentFilter` which rejects (ignores) all changes leading to an invalid value. – user85421 Jan 09 '17 at 10:42
  • @CarlosHeuberger Okay. Thanks. I'll try that. But to be more specific, I want that the user should not be able to add a value that is more than 256. – Vibhav Chaddha Jan 09 '17 at 11:06
  • it is a bit more work than what I did above: first you must find the new value and than only call the corresponding FilterBypass methods if the new value is not larger than 256 – user85421 Jan 09 '17 at 11:09
  • @CarlosHeuberger Okay. Thanks a lot. – Vibhav Chaddha Jan 09 '17 at 12:05
10

Use a JFormattedTextField.

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

jzd
  • 23,473
  • 9
  • 54
  • 76
3

Use a Document implementation whose insertString method filters out the non-digit characters.

Paŭlo Ebermann
  • 73,284
  • 20
  • 146
  • 210
1

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();
              }
         }
    });
}    
Mahfuz Ahmed
  • 721
  • 9
  • 23
0

Try out this DocumentFilter:

import javax.swing.text.*;
import java.awt.*;

public class IntegerDocumentFilter extends DocumentFilter
{
    private AbstractDocument abstractDocument;

    private IntegerDocumentFilter(AbstractDocument abstractDocument)
    {
        this.abstractDocument = abstractDocument;
    }

    @Override
    public void replace(FilterBypass filterBypass, int offset,
                        int length, String input, AttributeSet attributeSet)
            throws BadLocationException
    {
        int inputLength = input.length();

        String text = abstractDocument.getText(0, abstractDocument.getLength());
        int newLength = text.length() + inputLength;

        if (isNumeric(input) && newLength <= 8)
        {
            super.replace(filterBypass, offset, length, input, attributeSet);
        } else
        {
            Toolkit.getDefaultToolkit().beep();
        }
    }

    private boolean isNumeric(String input)
    {
        String regularExpression = "[0-9]+";
        return input.matches(regularExpression);
    }

    public static void addTo(JTextComponent textComponent)
    {
        AbstractDocument abstractDocument = (AbstractDocument) textComponent.getDocument();
        IntegerDocumentFilter integerDocumentFilter = new IntegerDocumentFilter(abstractDocument);
        abstractDocument.setDocumentFilter(integerDocumentFilter);
    }
}

Usage:

IntegerDocumentFilter.addTo(myTextField);
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185