Limiting Textfields in Java

后端 未结 4 594
暗喜
暗喜 2021-01-20 00:42

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

4条回答
  •  旧时难觅i
    2021-01-20 01:11

    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.

提交回复
热议问题