Java Swing: Implementing a validity check of input values

前端 未结 4 963
猫巷女王i
猫巷女王i 2020-12-31 16:08

In my Swing application, the user must insert numbers and values, before switching to the next window. Now as a clean program should, I check every input if its valid or not

4条回答
  •  悲哀的现实
    2020-12-31 16:52

    One solution would be to use Swing's InputVerifier to validate input for every JTextField used. As the validation functionality is the same for each field, a single instance could be used for all components:

    public class MyNumericVerifier extends InputVerifier {
        @Override
        public boolean verify(JComponent input) {
           String text = ((JTextField) input).getText();
           try {
              Integer.parseInt(text);
           } catch (NumberFormatException e) {
              return false;
           }
    
           return true;
        }
    }
    
    InputVerifier verifier = new MyNumericVerifier()
    textField1.setInputVerifier(verifier);
    

提交回复
热议问题