10

How can I disable input of any symbol except digits to JTextField?

Dhanuka
  • 2,826
  • 5
  • 27
  • 38
maks
  • 5,911
  • 17
  • 79
  • 123
  • possible duplicate of [Java JTextfields](http://stackoverflow.com/questions/4442004/java-jtextfields) – jjnguy Feb 01 '11 at 14:42
  • possible duplicate of [Is there any way to accept only numeric values in a JTextField?](http://stackoverflow.com/questions/1313390/is-there-any-way-to-accept-only-numeric-values-in-a-jtextfield) – Mark Peters Feb 01 '11 at 14:47
  • It sounds as though a JSpinner *might* be what the user actually needs here. – Andrew Thompson Feb 02 '11 at 15:53

7 Answers7

24

Option 1) change your JTextField with a JFormattedTextField, like this:

try {
   MaskFormatter mascara = new MaskFormatter("##.##");
   JFormattedTextField textField = new JFormattedTextField(mascara);
   textField.setValue(new Float("12.34"));
} catch (Exception e) {
   ...
}

Option 2) capture user's input from keyboard, like this:

JTextField textField = new JTextField(10);
textField.addKeyListener(new KeyAdapter() {
   public void keyTyped(KeyEvent e) {
      char c = e.getKeyChar();
      if ( ((c < '0') || (c > '9')) && (c != KeyEvent.VK_BACK_SPACE)) {
         e.consume();  // ignore event
      }
   }
});
gorlok
  • 1,155
  • 6
  • 16
8

The answer is JFormattedTextField. See my answer on this duplicate question:

You can use a JFormattedTextField. Construct it using a NumberFormatter and it will only accept numbers.

The JFormattedTextField has a bunch of configurable options that let you decide how bad input is handled. I recommend looking at the documentation.

Community
  • 1
  • 1
jjnguy
  • 136,852
  • 53
  • 295
  • 323
3

How to Use Formatted Text Fields

 amountField = new JFormattedTextField(NumberFormat.getIntegerInstance());

You can also create your own format to customize.

Mark Peters
  • 80,126
  • 17
  • 159
  • 190
3

Just consume all chars that is not a digit like this:

public static void main(String[] args) {
    JFrame frame = new JFrame("Test");

    frame.add(new JTextField() {{
        addKeyListener(new KeyAdapter() {
            public void keyTyped(KeyEvent e) {
                if (!Character.isDigit(e.getKeyChar()))
                    e.consume();
            }
        });
    }});

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(400, 300);
    frame.setVisible(true);
}
dacwe
  • 43,066
  • 12
  • 116
  • 140
  • 1
    That wont handle, for example, paste. It's also rather dependent upon how the PL&F implements the `JTextField` - wouldn't work for a `JComboBox` (probably!). – Tom Hawtin - tackline Feb 01 '11 at 14:58
3

For a better user experience

Others have mentioned the use of JFormattedTextField or KeyListeners to prevent invalid data from being entered but from a usability point of view I find it very annoying to start typing into a field and nothing happens.

To provide a better user experience you can allow the user to enter non-numeric values in the field but use a validator to provide feedback to the user and disable the submit button.

KevinS
  • 7,715
  • 4
  • 38
  • 56
0

This worked for me. Have a look.

public void keyTyped(KeyEvent e)
{

  char c = e.getKeyChar();

  if (!((c >= '0') && (c <= '9') ||    
     (c == KeyEvent.VK_BACK_SPACE) ||
     (c == KeyEvent.VK_DELETE))) {

        getToolkit().beep();

        e.consume();

  }

}
Marc-Andre
  • 912
  • 1
  • 15
  • 34
devKeshav
  • 41
  • 1
  • 5
0

You can add a custom KeyListener that intercepts key strokes and doesn't propogate invalid key strokes to the JTextField.

Qwerky
  • 18,217
  • 6
  • 44
  • 80
  • when i use keylisteners, the symbol will appear in field and after that it will be remove. But I want only the symbol to appear if it is a digit symbol – maks Feb 01 '11 at 14:48
  • If your listener consumes the `KeyEvent` then the field never hears about it. I see that dacwe has added just such an example. – Qwerky Feb 01 '11 at 15:00