0

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user2097804
  • 1,122
  • 4
  • 13
  • 22
  • [How to Use Formatted Text Fields](http://docs.oracle.com/javase/tutorial/uiswing/components/formattedtextfield.html) – mre Aug 15 '13 at 14:03
  • You can use a KeyAdapter and consume keys you don't like. – MightyPork Aug 15 '13 at 14:04
  • Please have a look at this answer, regarding [how to allow introducing only digits in JTextField](http://stackoverflow.com/a/9478124/1057230) – nIcE cOw Aug 15 '13 at 14:13

1 Answers1

1

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

P. Lalonde
  • 694
  • 1
  • 7
  • 17
  • 3
    @user2097804, this may work, but it is no longer the recommended approach. The example code in the API is old. New versions of Swing not support better approaches. See the comments you can use either the formatted text field or the DocumentFilter. DO NOT use a KeyListener. – camickr Aug 15 '13 at 15:03