Search code examples
javainputjtextfield

how can i limit a value into a jtextfield without use a button?


How can I limit a value (int) into a jtextfield in Java? Without Jbutton or something like that, I want do this in the input of the textfield. I have tried use evt.getkeychar but this gives me only the value of a single character.


Solution

  • You can add key listener to the JTextField and override the keyreleased method. In the method, check if the there are non-digit characters in the text, if there are, get rid of them.

    public class LimitInputValue {
        public static void main(String[] args) {
            JFrame jframe = new JFrame();
    
            final JTextField jTextField = new JTextField();
    
            jframe.add(jTextField);
            jframe.pack();
            jframe.setVisible(true);
    
            jTextField.addKeyListener(new KeyAdapter() {
                @Override
                public void keyReleased(KeyEvent e) {
                    String value = jTextField.getText();
                    if (value == null || value.isEmpty()) return;
                    String newValue = "";
                    for (int i = 0; i < value.length(); ++i) {
                        if (Character.isDigit(value.charAt(i))) {
                            newValue += value.charAt(i);
    
                        }
                    }
                    jTextField.setText(newValue);
                }
            });
        }
    }