JSpinner的输入限制实现
最近使用了JSpinner,需要限制其中数字部分。
final SpinnerModel model = new SpinnerNumberModel(minNumber, minNumber, maxNumber, 1);
numberSpinner = new JSpinner(model);
// 允许输入
final JSpinner.NumberEditor editor = new JSpinner.NumberEditor(numberSpinner, "0");
numberSpinner.setEditor(editor);
final JFormattedTextField textField = ((JSpinner.NumberEditor)numberSpinner.getEditor()).getTextField();
textField.setEditable(true);//开启输入功能
// 开启输入的值的限制
final DefaultFormatterFactory factory = (DefaultFormatterFactory)textField.getFormatterFactory();
final NumberFormatter formatter = (NumberFormatter)factory.getDefaultFormatter();
formatter.setAllowsInvalid(false);// 此处对输入的有效性进行控制。若改为true,则不控制有效性