使用递增和递减按钮在 java Swing 中创建一个数字文本框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6435668/
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
Create a numeric text box in java Swing with increment and decrement buttons
提问by Balanivash
How can I create a numeric text box in java swing , which has two buttons (up and down) which increments and decrements the value in the text box respectively. Also this text box must be editable with ONLY NUMERIC VALUES. Something like this
如何在 java swing 中创建一个数字文本框,它有两个按钮(向上和向下),分别增加和减少文本框中的值。此外,此文本框必须可编辑,只有 NUMERIC VALUES。像这样的东西
I tried by placing two buttons near a text box and manually doing the operation on button click.
我尝试通过在文本框附近放置两个按钮并手动执行按钮单击操作。
Is there any other method in which I can do this in a better way and achieve a similar result as the first image.
有没有其他方法可以更好地完成此操作并获得与第一张图像类似的结果。
Thanks :)
谢谢 :)
回答by Harry Joy
回答by mKorbel
JSpinnerneed for allows numeric input only, required some hack for that in its Model, but your 2nd. picture looks like as two JButtons(with JButton#setFocucPainted(false)), and one JFormattedTextFieldwith number Format, with min/maxDecimalPaces, with roundingMode
JSpinner需要只允许数字输入,在它的模型中需要一些 hack,但是你的第二个。图片看起来像两个JButton(带有 JButton#setFocucPainted(false)),一个带有数字格式的JFormattedTextField,带有 min/maxDecimalPaces,带有 roundingMode
myDoubleFormat.setMinimumFractionDigits(2);
myDoubleForma.setMaximumFractionDigits(2);
myDoubleForma.setRoundingMode(RoundingMode.HALF_UP);
then Actionfrom JButton
will be
那么ActionfromJButton
将是
myFtdTextField.setValue(((Number) myFtdTextField.getValue()).doubleValue() +/- 0.1)