Create a numeric text box in java Swing with increment and decrement buttons

前提是你 提交于 2019-12-10 12:38:43

问题


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

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 :)


回答1:


Use JSpinner

How to use Spinners in java


Based on your comment:

SpinnerModel model = new SpinnerNumberModel(9.9, 1, 15, 0.1);     
JSpinner spinner = new JSpinner(model);



回答2:


JSpinner need 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 JFormattedTextField with number Format, with min/maxDecimalPaces, with roundingMode

myDoubleFormat.setMinimumFractionDigits(2);
myDoubleForma.setMaximumFractionDigits(2);
myDoubleForma.setRoundingMode(RoundingMode.HALF_UP);

then Action from JButton will be

myFtdTextField.setValue(((Number) myFtdTextField.getValue()).doubleValue() +/- 0.1)


来源:https://stackoverflow.com/questions/6435668/create-a-numeric-text-box-in-java-swing-with-increment-and-decrement-buttons

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