开发者

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

开发者 https://www.devze.com 2023-02-26 03:05 出处:网络
How to implement in Java ( JTextFi开发者_StackOverfloweld class ) to allow entering only digits?Add a DocumentFilter to the (Plain)Document used in the JTextField to avoid non-digits.

How to implement in Java ( JTextFi开发者_StackOverfloweld class ) to allow entering only digits?


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


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


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();
              }
         }
    });
}    


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消