Chathura Jayanath
Chathura Jayanath

Reputation: 3

Java textfield validation

I have to validate a java text field which takes only integer values with a maximum length of 10. Entering of other values must be skipped.

I tried this as following. on that case i cant typed full stop.

private void jTextField2KeyTyped(java.awt.event.KeyEvent evt) {                                     
        char c = evt.getKeyChar();

        if(!(Character.isDigit(c) || (c==KeyEvent.VK_BACK_SPACE)||(c==KeyEvent.VK_STOP ) )){
            getToolkit().beep();

            evt.consume();

            }

    }          

Upvotes: 0

Views: 4510

Answers (2)

Tim B
Tim B

Reputation: 41188

Use a JFormattedText field not a JTextField and you can then specify a mask to limit what can be entered (or user a number formatter to have it automatically parsed as a number for you).

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

Upvotes: 3

alex2410
alex2410

Reputation: 10994

For that purposes you can use DocumentFilter like next :

JTextField f = new JTextField(10);
((AbstractDocument)f.getDocument()).setDocumentFilter(new DocumentFilter(){
    Pattern pattern = Pattern.compile("\\d*");

    @Override
    public void replace(FilterBypass arg0, int arg1, int arg2, String arg3, AttributeSet arg4) throws BadLocationException {
        String text = arg0.getDocument().getText(0, arg0.getDocument().getLength())+arg3;
        Matcher matcher = pattern.matcher(text);
        if(!matcher.matches()){
            return;
        }
        if(text.length()>10){
            return;
        }
        super.replace(arg0, arg1, arg2, arg3, arg4);
    }
});

Upvotes: 3

Related Questions