Search code examples
javaswinguser-interfacejtextfield

Java: how to allow backspace being pressed in JTextField


I've made a JTextField that restricts characters being entered unless it's numbers, letter "e", or comma . But now I realised that it restricts backspace being pressed to. How can I change it? I'll add the code, where it checks what key is being pressed, below

for (JTextField tf : listOfFields)
         {
             String value = tf.getText();
             int n = value.length();
             if (ke.getKeyChar()>= '0' &&  ke.getKeyChar() <= '9' || ke.getKeyChar() == ','|| ke.getKeyChar() == 'e')
             {
                 tf.setEditable(true);
             }
             else
             {
               tf.setEditable(false);
             }
         }}});

Solution

  • To have a text field accept a numeric entry, you should use a JFormattedTextField:

    JFormattedTextField field = new JFormattedTextField(
        NumberFormat.getIntegerInstance());
    field.setColumns(12);
    

    To make it check both a localized number format (one that uses commas) and also the java.lang syntax (like 1e5), you can create a NumberFormatter which does both:

    NumberFormatter formatter = new NumberFormatter() {
        @Override
        public Object stringToValue(String text)
        throws ParseException {
            try {
                return Double.valueOf(text);
            } catch (NumberFormatException ne) {
                return super.stringToValue(text);
            }
        }
    };
    JFormattedTextField field = new JFormattedTextField(formatter);
    field.setColumns(12);
    

    Each field’s value can be retrieved with the getValue method:

    for (JFormattedTextField tf : listOfFields) {
        Number value = (Number) tf.getValue();
        // ...
    }
    

    Restricting the keys typed by the user is not the correct way to guarantee numeric entry. For instance, your code would allow a user to type 123,4,45,678.

    There are many keys which allow editing. Home, End, Delete, and Ctrl-A are just a few. You shouldn't try to explicitly accommodate them all with a keystroke whitelist. Let JFormattedTextField do the work of verifying the input.