2

Possible Duplicate:
Restricting JTextField input to Integers
Detecting JTextField “deselect” event

i need to validate a JTextField by allowing the user to input only integer values in it if user enters any char other than numbers a JOptionPane.show messagebox should appear showing that the value entered are incorrect and only integer numbers are allowed. I have coded it for a digit values but i also need to discard the alphabets

public void keyPressed(KeyEvent EVT) {
    String value = text.getText();
    int l = value.length();
    if (EVT.getKeyChar() >= '0' && EVT.getKeyChar() <= '9') {
        text.setEditable(true);
        label.setText("");
    } else {
        text.setEditable(false);
        label.setText("* Enter only numeric digits(0-9)");
    }
}
Community
  • 1
  • 1
Sumeet Gavhale
  • 800
  • 4
  • 13
  • 39

3 Answers3

6

Instead of using a JFormattedTextField, you may write a custom JTextField with a document that allows only integers. I like formatted fields only for more complex masks... Take a look.

import javax.swing.JTextField;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.PlainDocument;

/**
 * A JTextField that accepts only integers.
 *
 * @author David Buzatto
 */
public class IntegerField extends JTextField {

    public IntegerField() {
        super();
    }

    public IntegerField( int cols ) {
        super( cols );
    }

    @Override
    protected Document createDefaultModel() {
        return new UpperCaseDocument();
    }

    static class UpperCaseDocument extends PlainDocument {

        @Override
        public void insertString( int offs, String str, AttributeSet a )
                throws BadLocationException {

            if ( str == null ) {
                return;
            }

            char[] chars = str.toCharArray();
            boolean ok = true;

            for ( int i = 0; i < chars.length; i++ ) {

                try {
                    Integer.parseInt( String.valueOf( chars[i] ) );
                } catch ( NumberFormatException exc ) {
                    ok = false;
                    break;
                }


            }

            if ( ok )
                super.insertString( offs, new String( chars ), a );

        }
    }

}

If you are using NetBeans to build your GUI, you just need to put regular JTextFields in your GUI and in the creation code, you will specify the constructor of IntegerField.

davidbuzatto
  • 9,207
  • 1
  • 43
  • 50
1

There is a componant for that: formatted textfield: http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html

JEY
  • 6,973
  • 1
  • 36
  • 51
1

Use JFormattedTextField capabilities. Have a look at example.

Ioan
  • 5,152
  • 3
  • 31
  • 50