java 使 JSpinner 完全数字化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6449350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 15:55:31  来源:igfitidea点击:

Make JSpinner completely numeric

javaswingtextboxnumericjspinner

提问by Balanivash

I've a Jspinner that can vary from minimumto maximumat steps of 0.1. This is working perfectly fine. Now, I set the editor of JSpinneras NumberEditoras the user can edit the textbox and I want only numeric values from this. This is also working, that is whatever the user may enter, the editor gives me only the numbers in the editor when I get the value using mySpinner.getValue().toString();. Now cones the problem. I want the textbox to accept only numeric values and .(decimal point), that is, if the user tries to enter anything apart from 0-9and ., it should not echo it in the textbox.

我有一个JSpinner的,可以从改变minimummaximum的步骤0.1。这工作得很好。现在,我设置的编辑JSpinnerNumberEditor作为用户可编辑的文本框,我想从这个唯一数值。这也有效,即无论用户输入什么,当我使用mySpinner.getValue().toString();. 现在解决问题。我希望文本框只接受数字值.(decimal point),也就是说,如果用户尝试输入除0-9and之外的任何内容.,则不应在文本框中回显它。

JSpinner mySpinner = new JSpinner();
mySpinner.setModel(new SpinnerNumberModel(default,minimum,maximum,0.1));
mySpinner.setEditor(new JSpinner.NumberEditor(mySpinner,"##.#"));

Can someone help me with this. Thanks :)

有人可以帮我弄这个吗。谢谢 :)

回答by Dilini Rajapaksha

You could try setAllowsInvalid(false)as follows:

你可以尝试setAllowsInvalid(false)如下:

JFormattedTextField txt = ((JSpinner.NumberEditor) mySpinner.getEditor()).getTextField();
((NumberFormatter) txt.getFormatter()).setAllowsInvalid(false);

By setting this property, the Jspinner will show only valid values in the field and ignores all other values entered by the user. also the user will not be able to delete the whole value entered in the Jspinner i.e. if the user tries to select the entire value and delete it will not be allowed. User can edit the field only with a valid value other wise the it will seem like un-editable.

通过设置此属性,Jspinner 将仅显示字段中的有效值,而忽略用户输入的所有其他值。此外,用户将无法删除在 Jspinner 中输入的整个值,即,如果用户尝试选择整个值并删除它,则不允许。用户只能使用有效值编辑该字段,否则它看起来不可编辑。