Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limiting Textfields in Java

Tags:

java

swing

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.

like image 739
Luke Avatar asked Dec 06 '22 03:12

Luke


1 Answers

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.

like image 167
Mark Avatar answered Dec 07 '22 17:12

Mark