Java examples for Swing:Text Input Verifier
Validating Text Input with InputVerifier
import javax.swing.InputVerifier; import javax.swing.JComponent; import javax.swing.JTextField; public class Main { public static void main(String[] args) { JTextField areaCodeField = new JTextField(3); areaCodeField.setInputVerifier(new InputVerifier() { public boolean verify(JComponent input) { String areaCode = areaCodeField.getText(); if (areaCode.length() == 0) { return true; } else if (areaCode.length() != 3) { return false; }//from w w w .j a v a2s. c o m try { Integer.parseInt(areaCode); return true; } catch (NumberFormatException e) { return false; } } }); } }