Avoiding JSpinner to take letters

点点圈 提交于 2019-12-11 10:42:41

问题


I have a jSpinner with a SpinnerNumberModel like this:

spinnerModelFix = new SpinnerNumberModel(0, 0, 65535, 1);
JSpinner fixedValueSpinner = new JSpinner(spinnerModelFix);

I just want to show Integers in the spinner, so that if the user insert letters they aren't shown.

I thought I should extends SpinnerNumberModel and override the fireStateChanged() method...

But I'm not sure what I need to do in that method.

Can anyone give me some hint?


回答1:


  • yes is possible and workaround is quite simple,

  • there are two ways how to do it, have to derive JTextField or JFormattedTextField from JSpinner,

  • then to add

    a) DocumentListener

    b) DocumentFilter

I think that usage of DocumentFilter is easiest for code workaround, better, maybe safer




回答2:


You can try setAllowsInvalid(false) on spinner's formatter. For example:

SpinnerNumberModel spinnerModelFix = new SpinnerNumberModel(0, 0, 65535, 1);
JSpinner fixedValueSpinner = new JSpinner(spinnerModelFix);
JFormattedTextField textField = ((JSpinner.NumberEditor) fixedValueSpinner
        .getEditor()).getTextField();
((NumberFormatter) textField.getFormatter()).setAllowsInvalid(false);


来源:https://stackoverflow.com/questions/12825622/avoiding-jspinner-to-take-letters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!