Setting enterable characters in JTextField

151 views Asked by At

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.

1

There are 1 answers

1
P. Lalonde On BEST ANSWER

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