Limiting Textfields in Java

java, swing

Solution

If you must use a text field you should use a JFormattedTextField with a NumberFormatter. You can set the minimum and maximum values allowed on the NumberFormatter.

NumberFormatter nf = new NumberFormatter();
nf.setValueClass(Integer.class);
nf.setMinimum(new Integer(0));
nf.setMaximum(new Integer(100));

JFormattedTextField field = new JFormattedTextField(nf);

However, Johannes suggestion of using a JSpinner is also appropriate if it suits your use case.

Problem

Is there a way to limit a textfield to only allow numbers 0-100, thereby excluding letters, symbols and such as well? I have found a way, but it is way more complicated than seems necessary.

Original source