Search code examples
javaswingjtextfielddocumentlistenerdocumentfilter

Setting enterable characters in JTextField


Is there any way to set what keys put characters in a JTextField?

For example, if I only wanted numbers to be entered, when a letter key is pressed, that letter would not be added to the existing text in the JTextField.


Solution

  • By setting a custom Document in your JTextField that would insert only numeric values in it.

    As shown in Oracle documententation about JTextField:

    public class UpperCaseField extends JTextField {
    
     public UpperCaseField(int cols) {
         super(cols);
     }
    
     protected Document createDefaultModel() {
         return new UpperCaseDocument();
     }
    
     static class UpperCaseDocument extends PlainDocument {
    
         public void insertString(int offs, String str, AttributeSet a)
             throws BadLocationException {
    
             if (str == null) {
                 return;
             }
             char[] upper = str.toCharArray();
             for (int i = 0; i < upper.length; i++) {
                 upper[i] = Character.toUpperCase(upper[i]);
             }
             super.insertString(offs, new String(upper), a);
         }
     }
    

    }

    Read more: http://docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.html